Running jQuery validate plugin internally

There are many articles on how to write your own rules for the jQuery validate plugin, but few of them explain the internal operation of this plugin, which we will discuss in this article.
This is the first part of a series of articles “Understanding the Unobtrusive Validation of Asp.NET MVC”

1. Operation of the jQuery validate plugin from the inside
2. Understanding the HTML code generated by the unobtrusive validation in ASP.Net MVC
3. The internal operation of the unobtrusive jQuery validate plugin in ASP.Net MVC.

What we learn from this article:
1. How to validate the form.
2. Validation messages and how they work.
3. Adding your own validation rules.
4. What exactly happens when we call the validation method.

How to validate a form


There are 2 main ways to validate a form.

1. Use class names as rules

How it works

We add to the field that we need to validate the html attribute “class”, and this will enable validation.
So, if we need the text field to be required, we add the class = “required” Html attribute value to the input element


<formaction="/"method="post"><inputid="Name"type="text"name="Name"value=""class ="required"  /><inputtype="submit"value="Submit" /></form>


Javascript
$(document).ready(function() {
  $('form').validate();
});

So you can add some rules to certain classes.

Pros and cons of this approach:
Works only with rules that take no arguments.
We use the html attribute “class” for what it is not intended for.
But it is easy to install.

Using the addClassRules Method

Using the addClassRules function enables us to use a compound rule for one class.

Javascript
 $.validator.addClassRules({
  name: {
    required: true,
    minlength: 2
  },
  zip: {
    required: true,
    digits: true,
    minlength: 5,
    maxlength: 5
  }
});

This code adds 2 new rules for the "name" and "zip" classes, and if we have an "input" element that has a "zip" class, then the rules apply to it: its value is mandatory, the user can enter only numbers and the length must be exactly 5 characters.

Html
<inputclass="zip"type="text"name="zipCode" />

Information: To use our own message for a specific rule requires in a composite rule, we need to come up with an alias for the “required” rule, create a new rule with this alias and set a default message for it.

Javascript
$.validator.addMethod("newrequired", $.validator.methods.required, "new name is required");

Or we can use the html attribute “title”, its value will be an error message for a compound rule.

Note: Class name validation only works for validation rules that take no arguments.

2. Adding rules as a JSON object to the validate () method

By name, you should have guessed that this validation method accepts a json object, so we can define the fields that we need to validate and the validation rules for them.

Html
<form><inputid="something"type="text"name="userEmail" /><inputid="submit"type="submit"value="submit" /></form>

Javascript
$('form').validate({
  rules: {
    userEmail: {
      email: true,
      required: true
    }
  }
});

Note: When we pass the rules object to the validate function, the key should be the value of the attribute name, not the value id. As you can see in the example: the key is “userEmail”, the value of the attribute “name”, and the attribute “id” has a different value.

Pros and cons of this approach:

This approach gives us the opportunity to use more validation rules that take arguments, such as minlength, remote, equalTo, etc.
Excellent and manually adjustable control over everything.
But the user has to do a separate "validate" function with different options for each form.

Add or remove dynamic rules.

Adding Rules

To add a rule, we must use the "rules" method for jQuery elements after the form is validated and pass the "add" string as the first parameter and as the second parameter the rules object that we want to add to this element (we can also pass the "message" object "For the rules we added).

Javascript
$('.input').rules('add', {
  required: true,
  messages: {
    required: true
  }
})

Deleting Rules

If we want to remove a rule or set of rules, we pass the string “remove” as the first parameter to the rules method, and the second parameter is the string that contains the rules that we want to remove, separated by a space.

Javascript
$('.input').rules('remove', 'min max');


Manual setup approach

Javascript
var validator = $('form').data('validator'); 
validator.settings.rules.objectName = {
  required: true
}

This approach is very useful if you have created rules and message objects, you can extend the validator rules with your own:

JavaScript
$.extend(validator.settings, { rules: rules, messages: messages });

Validation Messages and How They Work


There are three ways to configure a validation message

1. Pass the “messages” object to the “validate” method. The messages object consists of key \ value pairs. The key is the value of the "name" attribute of the element. Value is an object containing each rule and its message.

Javascript
$('form').validate({
  rules: {
    userEmail: {
    email: true,
    required: true
    }
  },
  messages: {
    userEmail: {
    email: "Please enter your email",
    required: "*"
    }
  }
});

2. Define the value of the “title” attribute of the Html element


<inputid="Email"title="you have to enter a value"type="text"name="Email" />

3. Use the default message. When a validation rule is defined, there are default built-in messages for built-in rules.

Note: These three methods override each other based on priority, the highest priority is the transmitted “messages” object, and the lowest priority is the default message.

Adding custom validation rules


When we want to add more validation rules than are defined by default, we use the
$ .validator.addMethod method .

This method accepts the following as parameters:
  • rule name
  • function that performs validation;
  • default message.

A function that performs validation can be with two or three JavaScript parameters


functionvalidationMethod (value, element)
// ORfunctionvalidationMethod (value, element, params)

Let's explain these options.
Value: the DOM value of the element that will be validated.
Element: the DOM element itself.
Parameters: what we pass as the value. For this example, validation rules are what params should equal.

Javascript
$('form').validate({
  rules: {
    firstname: {
      compare: {
        type: "notequal",
        otherprop: "lastname"
      }
    }
  }
});  

in this example, params will be equal to {type: "notequal", otherprop: "lastname"}

Example of adding your own rule:

JavaScript
$.validator.addMethod("notnumbers", function(value, element) {
  return !/[0-9]*/.test(value);
},
"Please don't insert numbers.")


What exactly happens when we call the validate method



When we invoke the validate method on the form, many different things happen behind the scenes:

A validator object is created with all the rules and options attached to the form.
The validate method attaches a validator using $ .data. We can get it by selecting the form and calling the jQuery "$ .data" function and passing it a "validator". The vaidator object is all the metadata for validation that gives us the ability to access the validation options at any time in the page life cycle.
Using this object, we can change at run time the options that we passed to the validation method, such as adding or removing rules, changing behavior if the field is valid or invalid, or even introducing an ignore selector.

Javascript
//getting the validatorvar validator = $("selector").data("validator")

Note: When you call the validate method on a form that has already been validated, it will only return the validator object, $ .data is also used, and all previous options passed by the validate method will be erased.

Javascript
var validator = $(".selector").validate(/* rules will be omitted */)

Attaching Form Events

What happens when we click submit (submit the form) and the wrong value is entered in the form for the field to which we attached the validation. If one of the fields is invalid, then the validation plugin will look more closely at it to check whether it is valid or not, according to events in this field.
Events of the form that the plugin subscribes to are “click”, “focusin”, “focusout”, “keyup”, “submit”.
Note: You can disable validation for certain events by passing them as keys in the validate method, and false as values.

Javascript
$(".selector").validate({
    onfocusout: false,
     onkeyup: false,
     onclick: false,
     onsubmit: false
});


Translation of Nadeem Khedr's article, How the jQuery validate plugin works internally. nadeemkhedr.wordpress.com/2012/08/12/how-the-jquery-validate-plugin-works-internally/#goCallValidate

update 06/01/13: Added links to other posts in the series

Also popular now: