A more involved example
Note that with HTML5 it is already possible to set a field as required by adding the required keyword to the input and you can also force fields to be treated as email, or phone. However, the browser will then take over the validation. You could argue that this is best practice, but for the sake of the example code below and my wish to create error messages that you can style yourself, I chose to do it this way.
Setting up the module
So the first thing I do is create a variable formValidation and set it to an immediately executed anonymous function.
The function only returns one thing: an object with one method init. This means that after execution of this code, formValidation has one public method init. Calling it (with formValidation.init()), will execute the function init inside the module, which in this case, only calls the function bindEvents. And this is where jQuery comes in.
We bind a blurHandler to the blur event and a clickHandler to the click event. But wait a minute, to what elements are these events bound? The part $(datajs(‘req’, ‘required’)) is a normal jQuery selector that we pass a function datajs with two arguments. datajs just finds the element in the page that have a data-x attribute with value y, where (x,y) are the arguments of the function. So basically, $(datajs(‘req’, ‘required’)) selects the elements having a data attribute ‘req’ with the value ‘required’. A similar selection takes place for the input with data attribute ‘type’ and value ‘submit’.
jQuery events: blur and click handlers
So what happens when we blur out of a field or click the submit button? Right, the corresponding handlers are called. The blurHandler will check the value of one input field and its type and then calls the function validateField. The clickHandler checks all the fields in a for loop. It does this by looking at the config object to know which fields to include. So here we are with a close coupling between the module and the HTML. Not very nice at this point, so perhaps it is better to just give the form itself a data attribute and get all elements from the form that way.
So the real validation of a field is now the last task to implement. This function (validateField) will check the value of the input field with respect to our validation rules. For example, here I have defined these rules as required fields may not be empty, with on top of that, email fields should have a valid email address and phone number fields should have a valid (dutch) phone number. As soon as an error occurs the function returns an object showing what went wrong.
The functions to check for valid emails and phone numbers are just simple regular expressions and are testable with a simple unit test. Since this post is already quite lengthy, we leave the unit testing to a follow up post.