Javascript modules and jQuery events

In a recent post on Javascript modules I explained the importance of writing good Javascript code. A first step achieving this goal is to start writing modules in Javascript. Modules make way for structured, organised code that does one thing and one thing well. If you write your Javascript in modules your code is easier to maintain, test and scale.

The post ended with a very simple calculation module and the promise of writing about including jQuery events and unit testing. This is the subject for today’s post. With the update of our website at PLint-sites, I improved the Javascript by using modules. The module I would like to discuss in this blog is for validating a simple form. Although I would like to keep the coupling to the DOM as loose as possible in my Javascript, somehow we have to know which form fields are required. But instead of adding a class ‘required’, I rather use the HTML5 data attributes. This way, changing the classes will never affect the Javascript and it is also good to use classes and IDs for styling.

A more involved example

simple HTML formSo here we go with the jsFiddle below. First look at the HTML which is really simple. It consists of a form with some input elements and a submit button. I added a few lines of CSS to make it look a little better: it just gives me a better feeling to work on Javascript knowing that the HTML and CSS are done and I am satisfied with the looks. Note that I added specific data attributes to some fields, setting all fields as required and I added a data-type attribute for the email and phone number fields.

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.

I would like to do a form validation when the visitor is blurring on either of the input fields and when clicking on the submit button. But remember, I really want to use Javascript modules and I need the coupling to the HTML as loose as I can.

Setting up the module

So the first thing I do is create a variable formValidation and set it to an immediately executed anonymous function.

Return values

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.

Function validateField

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.

validate email

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.

required field

Conclusion

We created a simple HTML form with some required and specific form fields. Blurring the fields or clicking the submit handler triggers the Javascript form validation module. The module only returns a public init function for initialisation, the rest of the module functions are private. The functions inside the module are very small an just do one thing. In this setup, the module is nice and easy to read and extend if needed!


Mijn Twitter profiel Mijn Facebook profiel
Pim Hooghiemstra Webdeveloper and founder of PLint-sites. Loves to build complex webapplications using Vue and Laravel! All posts
View all posts by Pim Hooghiemstra

Leave a Reply

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