Documente Academic
Documente Profesional
Documente Cultură
This article discusses client-side validation using jQuery's validation plugin. This
jQuery Library.
JSP
<!DOCTYPE HTML>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.min.js"></scri
pt>
<title>Basic jQuery Validation</title>
</head>
<body>
<form id="myForm" name="" action="">
<label for="name">Name: </label> <input name="name"
size="20" />
<input class="submit" type="submit" value="Submit" />
</form>
</body>
<script>
$(function() {
$("#form").validate(
{
rules : {
name : {
required : true,
}
},
messages : {
name : {
required : "Please enter a name",
}
}
});
});
</script>
#form label.error {
color:red;
}
#form input.error {
border:1px solid red;
}
Lets add a bunch of new criteria such as minimum/maximum length and even
custom messages.
Ive also introduced the format method in the message. This lets us replace the
argument given for minlength and maxlength. Here we dont have to worry about
hard-coding that value if they ever change.
In some cases if I can't find a suitable built-in method for my situation. Then I Can write my own
validation method
This is a regex example to test for special characters. Here Im allowing some
special characters but others Im not. So if you enter * or ! for example, you
will get the message. Pretty cool huh?
These are the steps I went through to understand this plugin. Im certainly not an
expert (far from it) so comments are most welcome. I hope this can help you on
your way.
http://jqueryvalidation.org/documentation
http://www.sitepoint.com/jquery-ajax-validation-remote-rule/
http://www.codeproject.com/Articles/213138/An-Example-to-Use-jQueryValidation-Plugin
All we are doing here is initializing the validation of the form using the validate() function. It can take
several parameters. In the example above, we use only two of them, but you can find a list of all the
options for thevalidate() function at http://docs.jquery.com/Plugins/Validation/validate#toptions.
The two parameters we used are:
rules: allows you to specify which fields you want to validate. In this case, we are
validating name, email,url and comment. For each field, we specify if the field is required
(required: true). We can specify that it must be a valid e-mail address, URL, etc.
messages: allows you to specify the error message for a particular field (like the comments
field in the example above). If you don't specify it, a default message is provided that says "this
field is required".