Do we really need JQuery validator plugin?

The more I need to do some HTML client side validation the more I am asking myself whether we need a validation framework or not.

Until now I have not used any specific validation framework. But now I have to because I do not want to take care of simple syntax level (number field could accept numbers only, etc.) field validation.

First of all I have used developers best friend: Google . I have found numerous validation framework for JQuery (just have a look at the Google search result in the previous links).

I have check many of them and found that most of them are too complicated to my need (remember, I need simple syntax check because complex validation is made on server side).

The client side I wanted to make something simple and declarative:

1  <form:input path="duration.hour" cssClass="form-control" maxlength="2" data-validation-pattern="^([01]?[0-9]|2[0-3])?$"/>

This is a simple Spring MVC input field. I have just introduced a custom data attribute called data-validation-pattern and the value is the regex pattern I want the check actual value test against. This specific example is checking an optional field which is accepting hours (0-23) of a day.

The expected behavior is that when any error happens I do not want to submit the form.

1  $('#mrs_form').submit(function(event) {
2    var validator = new MeetingValidator('#mrs_form');
3
4    if (!validator.checkValidity()) {
5      event.preventDefault();
6    }
7  });

So far, so good.

Let’s implement the validator:

 1  function MeetingValidator(form_selector, options) {
 2    "use strict";
 3    var DEFAULT_OPTIONS = {
 4      on_finished : function() {}
 5    };
 6    options = $.extend({}, DEFAULT_OPTIONS, options);
 7    var issues = [];
 8
 9    /**
10     * @return false if there are validation errors
11     */
12    function checkValidity() {
13      checkRegexPattern();
14      options.on_finished(issues);
15      return _.isEmpty(issues);
16    }
17
18    function checkRegexPattern() {
19      $('[data-validation-pattern]', form_selector).each(function() {
20        var name = $(this).attr('name');
21        var patt = new RegExp($(this).data('validation-pattern'));
22        var value = $(this).val();
23        if (!patt.test(value)) {
24          issues.push({
25            kind : 'pattern',
26            name : name,
27            value : value
28          });
29        }
30      });
31    }
32    MeetingValidator.prototype.checkValidity = checkValidity;
33  }

Cool, isn’t it? In function checkRegexPattern there are 4 effective lines of code which is dealing with all what I need.

You could say: “But it is not enough I need to report errors to the user”. And I will say: “Yes, you are right!”

And here is the weakness of many validator plugins. They are not so flexible how to report the error. If you have a look at the code it has an optional input parameter called options with one relevant attribute called on_finished which is intended to be a function and called at the end of the validation process.

Let’s see in practice:

 1  $('#mrs_form').submit(function(event) {
 2    var validator = new MeetingValidator('#mrs_form', {
 3      on_finished : on_validation_finished
 4    });
 5
 6    if (!validator.checkValidity()) {
 7      event.preventDefault();
 8    }
 9  });
10
11  function on_validation_finished(issues) {
12    _.each(issues, function(issue) {
13      $('input[name="' + issue.name + '"]').parents('.form-group').addClass('has-error');
14    });
15  }

Function on_validation_finished is simply mark the field (using bootstrap styles).

Enjoy it!

Aug 04, 2014
comments powered by Disqus

Links

Cool

RSS