There are many articles on how to write your own rules for the jQuery validate plugin, but few of them explain the inner workings of this plugin, which we will discuss in this article.
This is the first part of the "Understanding the Unobtrusive Validation of Asp.NET MVC" series.
1. The jQuery validate plugin works from the inside
2. Understanding Html-code generated by unobtrusive validation in ASP.Net MVC3. Internal work of the jQuery validate unobtrusive 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. Add your own validation rules.
4. What exactly happens when we call the validation method.
')
How to validate a form
There are 2 basic ways to validate a form.
1. Use class names as rules
How it works
We add html attribute “class” to the field to be validated, and this will enable validation.
So, if we need the text field to be mandatory, we add the value of the attribute class = "required" to the input element
Html<form action="/" method="post"> <input id="Name" type="text" name="Name" value="" class ="required" /> <input type="submit" value="Submit" /> </form>
Javascript $(document).ready(function() { $('form').validate(); });
So you can add a few 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 allows us to use the composite 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 class “name” and “zip”, and if we have an “input” element whose class is “zip”, 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 <input class="zip" type="text" name="zipCode" />
Information: To use a custom 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 “title” attribute, its value will be an error message for the compound rule.
Note: Validation by class name 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> <input id="something" type="text" name="userEmail" /> <input id="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 must be the value of the “name” attribute, not the value “id”. As you can see in the example: the key is “userEmail”, the value of the attribute is “name”, and the attribute “id” is a different value.
Pros and cons of this approach:
This approach allows us to use more validation rules that take arguments, such as minlength, remote, equalTo, etc.
Excellent and customizable control over everything.
But the user must make a separate function “validate” 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 has been validated and pass the “add” string as the first parameter and the second parameter is the rule object that we want to add to this element (we can also pass the message object "For the rules that we added).
Javascript $('.input').rules('add', { required: true, messages: { required: true } })
Deleting rules
If we want to remove a rule or a 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 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 set up a validation message.
1. Transfer the “messages” object to the “validate” method. The “messages” object consists of key / value pairs. The key is the value of the element's “name” attribute. The 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. Determine the value of the attribute “title” element
Html <input id="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 built-in default 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 least priority is the default message.
Add your own validation rules
When we want to add more validation rules than are defined by default, we use the method
$ .validator.addMethodThis method takes as parameters the following:
- the name of the rule;
- the function that performs the validation;
- default message.
The function that performs validation can be with two or three parameters.
Javascript function validationMethod (value, element) // OR function validationMethod (value, element, params)
Let's explain these parameters.
Value: The value of the DOM element to be validated.
Element: the DOM element itself
Parameters: what we pass as value. For this example, the validation rules are what params should equal.
Javascript $('form').validate({ rules: { firstname: { compare: { type: "notequal", otherprop: "lastname" } } } });
in this example, params will be {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 call the validate method on a 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 appends the “validator” using "$ .data". We can get it by selecting the form and calling the jQuery function "$ .data" and passing it to the "validator". The “vaidator” object is all validation metadata that gives us the ability to access the validation options at any time during the page life cycle.
Using this object, we can change during the execution of options that we passed to the validation method, such as adding or deleting rules, changing behavior, if the field is valid or invalid, or even introducing an ignore selector.
Javascript
Note: When you call the “validate” method on a form that has already been validated, it will return only the “validator” object, $ .data is also used, and all previous options passed by the “validate” method will be erased.
Javascript var validator = $(".selector").validate()
Attaching Form Events
What happens when we click submit (submit the form), and the form will contain the wrong value for the field to which we have attached validation. If one of the fields is invalid, then the validation plug-in will look more closely at it, in order to check whether it is valid or not, by the events on this field.
The forms that the plugin subscribes to are “click”, “focusin”, “focusout”, “keyup”, “submit”.
Note: You can disable validation on 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 article "How the jQuery validate plugin works internally".
nadeemkhedr.wordpress.com/2012/08/12/how-the-jquery-validate-plugin-works-internally/#goCallValidateupdate 01.06.13: added links to other posts in the series