jQuery Validation Plugin can check the form for the correctness of the filled data in accordance with the specified rules and dynamically displays user errors.
jQuery Validation Plugin features:
- URL and E-mail checking;
- checking of the maximum and minimum values, ranges of numbers, dates;
- automatic display of errors.
How it works with the plugin
Let’s consider the operation of the plugin using the example of a simple login and password form.
An example of HTML form:
<form id=”loginform” action=”” method=”post”>
Your username:
<input type=”text” name=”login” />
Your password:
<input type=”password” name=”pswd” />
<input type=”submit” name=”enter” value=”Enter” /></form>
Connecting files and libraries:
Connecting jQuery libraries and the plugin on the page.
<script type=”text/javascript” src=”js/jquery-1.5.2.min.js”></script>
<script type=”text/javascript” src=”js/jquery.validate.min.js”></script>
JS
Then, the plugin
($(“#loginform”).validate())
is initialized for an HTML form with a given id.
Fields by names (name=”login”) are defined in “rules” attribute, and rules, according to which the validation will occur, are set for the specific field.
An error message text of validation is specified for each rule separately in the “messages” parameter.
CSS
To change the form of the error messages, you need to work with the class .error in CSS file
.error {
color: red;
}
List of rules
- required — a field should be filled obligatory (true or false);
- maxlength — maximum number of characters (a number);
- minlength — minimum number of characters (a number);
- email — verifying of the email address correctness (true or false);
- url — verifying of the url address correctness (true or false);
- remote — specifying a file for checking the field (for example: check.php);
- date — verifying of the date correctness (true or false);
- dateISO — verifying of the ISO date correctness (true or false);
- number — the number verifying (true or false);
- digits — only numbers (true or false);
- creditcard — a credit card number correctness (true or false);
- equalTo — equal to something (for example, to another field equalTo:»#pswd»);
- accept — verifying of correct extension (accept: «xls|csv»);
- rangelength — range of character lengths, minimum and maximum (rangelength: [2, 6]);
- range — a number should be within the range from to (range: [13, 23]);
- max — maximum number (22);
- min — minimum number (11).