jQuery Validate

jQuery Validation plugin is popular and simple plugin for client side validations. It can be customized with plenty of options. It can be easily integrated into your existing forms. The plugin already has set of useful validation methods including URL and email validation that come out of the box. The plugin provides an API to write your own methods. All in built methods comes with default error messages in english. In the blog, I will try to explore a few methods and usage of jQuery Validate Plugin. Plugin Methods This library adds three jQuery plugin methods:
  • validate() – Validates the selected form.
  • valid() – Checks whether the selected form or selected elements are valid.
  •  rules() – Read, add and remove rules for an element
Setting up: You need to download the files and then place dist/jquery.validate.min.js file in #= require jquery.validate.min Applying to the form:
  • You just need to add a class ‘jqvalidate’ to the form that you want to validate. In rails, you will generally do it like following
    <%=  form_for(@account, :html =&gt; { :class =&gt; "jqvalidate" }) do |f| %>
    .........
    .........
    <% end %>
    
  • Next you need to create a function that is to be called before the form is loaded:
    $.validate_form = () -&gt;
    $.validator.addClassRules({
    cc_number: { required: true, digits: true, minlength: 15, maxlength: 16},
    cc_cvv: { required: true, digits: true, minlength: 3, maxlength: 4}
    })
    $('.jqvalidate').validate({
    ignore: ".jqvalidate_ignore"
    errorClass: "invalid"
    })
    
  1. addClassRules is used to specify validations on the fields with its in built methods. cc_number and cc_cvv are the classes given to two different fields respectively on which the validations are applied.
  2. ‘.jqvalidate_validate’ class is given to those fields that are not subject to the validations by this plugin.
  3. ‘invalid’ is the class given to the error messages.
The blog post just details the start for the plugin. We encourage you to dig more and explore this great plugin. For more details, refer to the documentation.