Form Validation with jQuery from Scratch

The HTML form

There’s a pretty diverse opinion on how this should be done exactly, but we’ll make the code flexible enough to handle different markup styles.

This is how I markup my forms. Trying to keep it as simple and semantic as possible, but adding the div to make styling easier.

Specifying input validation

In HTML4 there is no obvious way attach validation rules to an input. A few developers have been somewhat orthodox and added their own “validation” attribute.

This is not valid HTML, but it works in all browsers, and maybe it’s better than using a valid attribute for the wrong reasons. It is up to you, but this is how I do it.

The validation object

The base validation object contains a set of methods and properties that only needs be stored in one place, but can be accessed globally. In object oriented terminology this is commonly referred to as a Singleton.

The object contains a set of rules, each with a function and a message. There’s also a function called “testPattern”. Being defined with the var keyword makes them private and inaccessible outside the object itself.

NOTE: I’ve simplified the regular expressions above to make the example readable. I suggest you take a look at the expressions from the official jQuery valide plugin for the real deal.

Adding the object to the jQuery $ namespace is useful because now we can access it like any other jQuery object, hence, it’ll be helpful later on in our plugin code.

Public methods

Instead of hard coding lots of rules, we keep it down to a minimum. We defined a method called “addRule” and made it public by wrapping it in a return statement. The concept of returning methods and properties to make them public is commonly referred to as the module pattern.

Adding additional validation rules

People can now use our method to quickly add new custom validation rules without having to modify our code.

We’ve now added a custom validation rule called “test”, maybe not so useful, but consider the next example. We add a rule to check whether a username is taken or not, with an imaginary AJAX request.

Some people will by now probably point out that the addRule method is essentially the same as making the object public and letting people add stuff to it themselves. Yes, that’s true, but this a VERY simple abstraction. Should the code get any more advanced an abstraction like this could be helpful for anyone using your code.

Take a look inside

Lets take a look at our object in the firebug console.

It should simply print out “object”. If you click it you will see the public methods we added earlier on. Let’s see what the getRule method produces.

As you will see, it returns the rule we added earlier. In OOP terminology we have now implemented getters and setters. Instead of allowing direct access to an objects private properties. It’s better to have public methods that make these changes. It produces a cleaner API to the end user and it gives us more flexibility in case something else needs to run when modifying a property.

But someone told me the module pattern sucks’

Although I prefer this style of coding, it should be said that some developers neglect the idea of hiding properties and methods (a.k.a data encapsulation) in JavaScript. I think there are some very legitimate arguments linked to that statement. I leave it up to you to make up your own mind, nevertheless it is good to have knowledge of different design patterns even if you don’t use them.

The form object

The form object will represent an instance of a form in the DOM.

A form has a number of fields belonging to it. We iterate over all the inputs and textareas that has a validation attribute using the jQuery each method. For each field there is, we create a new instance of the Field object which looks like this:

We have defined some properties using the this keyword which refers to the object itself. We can now create any number of “form”; instances with the new keyword.

Providing your forms actually contain some fields with a validation attribute, you should see some interesting results when printing the object in the firebug console.

The JavaScript prototype object

This may seem like a tricky concept at first, but once you can wrap your ead around prototypal inheritance, it’s a really powerful and useful feature of the JavaScript language.

The problem

We have a large number of instances of the Field object, all of which we need to add some methods to. At first it may seem like a perfectly good idea to do the following:

But this essentially means that if we have 30 fields instances, we will have 30 instances of the validate function, which is really a waste, since they all do the same thing.

The solution

Adding the validate method to the prototype object of Field will make all instances of Field inherit the validate method, but the validate method only exists in one place, so any changes to it will be reflected upon all instances of the Field object.

This feature should be used with care, especially when used on native javascript objects, before you fiddle around with it to much I recommend you read up further on the subject.

The Field validation methods

These are thetwo methods attached to the Field prototype object.

As a last step, we are going to edit the Field object we defined earlier:

Now each field will validate upon the “change” event.

Finishing the Form Object

Now our Field object is pretty much complete, let’s add a few more features to the Form object before moving on to the actual jQuery plugin implementation.

The jQuery plugin methods

We are going to use the jQuery extend method to make our plugin accessible as methods on any jQuery object.

The validation method is what we use to create a new validation instance associated to a form. You can see that we are creating a new form instance and also binding the a submit event handler to run the validation upon form submission.

The jQuery $.data method

This is pretty nifty feature and allows us to store data assoicated to a jQuery object. In this case, we are storing an instance of the form object inside the object passed into the plugin. In the validate method, that we use to validate the form at anytime, we can now call the already existing form instance, instead of creating a new one.


Based on the plugin that we have now built, here are some usage examples.

Leave a Reply

Your email address will not be published. Required fields are marked *