The 08/08/2016

Form validation with jQuery Validate

Want to check your form in javascript simply and quickly? You need a library that will allow you to verify that a field is an email, a credit card, an address or a zip code etc ...? You want to place your error messages where and how you want? Then this article will help!

In this article we will see how to set up a system of validation of your forms in JavaScript using the plugin 'jquery validate ".

You can see the plugin documentation on the official website of jquery at the following address:
http://docs.jquery.com/Plugins/Validation

Why use this method?
- Validate your client side forms (javascript) allows you not to use the server controls (EDITION TO PREVENT MISUNDERSTANDING: ATTENTION THEY MUST STILL BE PRESENT IF THE USER DISABLES JAVASCRIPT) and thus avoid overloading it.
- Validate jQuery is simple and fast.
- With this method, you can do whatever you want

In short, either way you are about to read this article and if you go to the end, you will be convinced of my choice by yourself :)

First, add the files ...
Begin adding jQuery (the base library it use) and the jQuery validate plugin in your page. You can find them at the following address:

- jQuery:
http://docs.jquery.com/Downloading_jQuery
take the file jquery-xxxx.min.js
(Xxx is the latest version - currently 1.5.1-)

- jQuery validate:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
take jquery.validate.min.js file

And insert it in your page :


<script type="text/javascript" src="jquery-xxxx.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>

Second, how does it work?

Imagine that our form to the following id: myForm



<form id="myForm" method="post" action="#">
   <textarea id="mon_textarea" name="montextarea"></textarea>
   <input type="email" id="mon_email" name="monemail" />
   <input type="email" id="mon_telephone" name="montelephone" />
   <input type="submit" value="ok" id="btn_submit" />
</form>

To validate the form :


<script>
   $(document).ready(function(){
      $("#myForm").validate();
    });
</script>

to define the rules, we will use a simple syntax:


jQuery(document).ready(function() {
   jQuery("#formStep").validate({
      rules: {
         "montextarea":{
            "required": true,
            "minlength": 2,
            "maxlength": 60000
         },
         "monemail": {
            "email": true,
            "maxlength": 255
         },
         "montelephone": {
            "required": true
         }
  })
});

Tips 1: Define error messages

here is an easy way to override a method:


  jQuery.extend(jQuery.validator.messages, {
    required: "votre message",
    remote: "votre message",
    email: "votre message",
    url: "votre message",
    date: "votre message",
    dateISO: "votre message",
    number: "votre message",
    digits: "votre message",
    creditcard: "votre message",
    equalTo: "votre message",
    accept: "votre message",
    maxlength: jQuery.validator.format("votre message {0} caractéres."),
    minlength: jQuery.validator.format("votre message {0} caractéres."),
    rangelength: jQuery.validator.format("votre message  entre {0} et {1} caractéres."),
    range: jQuery.validator.format("votre message  entre {0} et {1}."),
    max: jQuery.validator.format("votre message  inférieur ou égal à {0}."),
    min: jQuery.validator.format("votre message  supérieur ou égal à {0}.")
  });
  
Tips 2: Add Method - Regular Expression (regex)

Here we use the method addMethod to add a rule with a regular expression


jQuery.validator.addMethod(
  "regex",
   function(value, element, regexp) {
       if (regexp.constructor != RegExp)
          regexp = new RegExp(regexp);
       else if (regexp.global)
          regexp.lastIndex = 0;
          return this.optional(element) || regexp.test(value);
   },"erreur expression reguliere"
);

For using it, nothing more simple, just add the rule "regex" like any other attributes

"montelephone": {
    "required": true,
    "regex": /^(\+33\.|0)[0-9]{9}$/
}

Tips 3: Change a behaviour

Say you want to perform an action when submit your form, for example hide the submit button when the user send valid information and the validated form is submitted.

rules:{
    ...
},
submitHandler: function(form)
{
    /* CACHER LE BOUTON */
    jQuery("#btn_submit").hide();
}

The same way you can override other actions (see the doc, and google is your friend!) when the form is invalid ( invalidHandler : function (form, validator) {}) or when displays an error ( errorPlacement : function (error, element) {} - very convenient to redefine the placement of the error message)

PS: It is also possible to define messages and validation rules other way but for me this one is the best because everything is concentrated on a few lines javascript and you do not have to open 40000 files in order to change these behaviors.

And here we arrive at the end of this article, I hope you liked and that will help. Feel free to put your comments Pierre
Comments on this article
No comments yet for this article. Be the first !

You must be logged in to comment an article.