jQuery Validation


There are a lot of client side form validation plugin. Right, there are a lot of non-jQuery-based solutions (which you’d avoid since you found jQuery) and some jQuery-based solutions. Here, I will discuss about one of the oldest jQuery plugins, jQuery Validation, (started in July 2006) and which proved itself in projects all around the world. Look at the example below:

Please provide your name, email address (won’t be published) and a comment









Click on the above submit button and see what happen(in case of incomplete/mistake). Don’t you like this? It works nice. Let us introduce with this nice plugin to get a efficient html form.
Here I will only introduce you with jQuery Validation Plugin and then provide few links for your advance learning. Look at the code for the above form:
<form id="commentForm" class="cmxform" action="" method="get">
<fieldset><legend>Please provide your name, email address (won’t be published) and a comment</legend>
<label for="cname">Name (required)</label>
<input id="cname" type="text" name="name" />
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" />
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
<label for="ccomment">Your comment (optional)</label>
<textarea id="ccomment" name="comment"></textarea>
<input class="submit" type="submit" value="Submit" />
</fieldset>
<span>Click on the above submit button and see what happen. Don’t you like this? It works nice. Let us introduce with this nice plugin to get a efficient html form.</span>
</form>
Here I used the following css file and plugins (jQuery Validation Plugin):
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
I also used the following scripts:
<script>
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
$().ready(function() {
// validate signup form on key-up and submit
$("#commentForm").validate({
//Name of the field: "required" (if required)
rules: {
name: "required",
firstname: "required",
lastname: "required",
username: {
required: true,
minlength: 2
},
password: {
required: true,
minlength: 5
},
confirm_password: {
required: true,
minlength: 5,
equalTo: "#password"
},
email: {
required: true, email: true
},
topic: {
required: "#newsletter:checked",
minlength: 2
},
agree: "required"
},
messages: {
//Name of the field: "Write any message"
name: "Please enter your name",
firstname: "Please enter your firstname",
lastname: "Please enter your lastname",
username: {
required: "Please enter a username",
minlength: "Your username must consist of at least 2 characters"
},
password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long"
},
confirm_password: {
required: "Please provide a password",
minlength: "Your password must be at least 5 characters long",
equalTo: "Please enter the same password as above" },
email: "Please enter a valid email address", agree: "Please accept our policy"
}
});
});
</script>
Here is a small description of the above scripts (jQuery Validation):

jQuery Validation

Description: Validates the selected form.

validate( [options ] )

options
Type: Object
debug (default: false)
Type: Boolean
Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if a window.console property exists). Try to enable when a form is just submitted instead of validation stopping the submit.Example: Prevents the form from submitting and tries to help setting up the validation with warnings about missing methods and other debug messages.
$(".selector").validate({
debug: true
});
submitHandler (default: native form submit)
Type: Function()
Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it validated.Example: Submits the form via Ajax when valid.
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
Example: Use submitHandler to process something and then using the default submit. Note that “form” refers to a DOM element, this way the validation isn’t triggered again.
$(".selector").validate({
submitHandler: function(form) {
// do other stuff for a valid form
form.submit();
}
});
The callback gets passed one argument:
form
Type: Element
The form currently being validated, as a DOMElement.
invalidHandler
Type: Function()
Callback for custom code when an invalid form is submitted. Called with a event object as the first argument, and the validator as the second.Example: Displays a message above the form, indicating how many fields are invalid when the user tries to submit an invalid form.
$(".selector").validate({
invalidHandler: function(event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'You missed 1 field. It has been highlighted'
: 'You missed ' + errors + ' fields. They have been highlighted';
$("div.error span").html(message);
$("div.error").show();
} else {
$("div.error").hide();
}
}
});
The callback gets passed two arguments:
event
Type: Event
A custom event object, since this function is bound as an event handler.
validator
Type: Validator
The validator instance for the current form.
ignore (default: ":hidden")
Type: Selector
Elements to ignore when validating, simply filtering them out. jQuery’s not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements.Example: Ignores all element with the class “ignore” when validating.
$("#myform").validate({
ignore: ".ignore"
});
rules (default: rules are read from markup (classes, attributes, data))
Type: Object
Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String. Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions. See the second example below for details.Example: Specifies a name element as required and an email element as required (using the shortcut for a single rule) and a valid email address (using another object literal).
$(".selector").validate({
rules: {
// simple rule, converted to {required:true}
name: "required",
// compound rule
email: {
required: true,
email: true
}
}
});
Example: Specifies a contact element as required and as email address, the latter depending on a checkbox being checked for contacting via email.
$(".selector").validate({
rules: {
contact: {
required: true,
email: {
depends: function(element) {
return $("#contactform_email:checked")
}
}
}
}
});
messages (default: the default message for the method used)
Type: Object
Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator and with the rule’s parameters as the first and the element as the second argument, it must return a String to display as the message.Example: Specifies a name element as required and an email element as required and a valid email address. A single message is specified for the name element, and two messages for email.
$(".selector").validate({
rules: {
name: "required",
email: {
required: true,
email: true
}
},
messages: {
name: "Please specify your name",
email: {
required: "We need your email address to contact you",
email: "Your email address must be in the format of name@domain.com"
}
}
});
Example: Validates the name-field as required and having at least two characters. Provides a callback message using jQuery.format to avoid having to specify the parameter in two places.
$(".selector").validate({
rules: {
name: {
required: true,
minlength: 2
}
},
messages: {
name: {
required: "We need your email address to contact you",
minlength: jQuery.format("At least {0} characters required!")
}
}
});
groups
Type: Object
Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use error Placement to control where the group message is placed.Example: Use a table layout for the form, placing error messages in the next cell after the input.
$("#myform").validate({
groups: {
username: "fname lname"
},
errorPlacement: function(error, element) {
if (element.attr("name") == "fname" || element.attr("name") == "lname" ) {
error.insertAfter("#lastname");
} else {
error.insertAfter(element);
}
}
});
onsubmit (default: true)
Type: Boolean
Validate the form on submit. Set to false to use only other events for validation.Set to a Function to decide yourself when to run validation.A Boolean true is not a valid value.Example: Disables onsubmit validation, allowing the user to submit whatever he wants, while still validating on keyup/blur/click events (if not specified otherwise).
$(".selector").validate({
onsubmit: false
});
onfocusout
Type: Boolean or Function()
Validate elements (except checkboxes/radio buttons) on blur. If nothing is entered, all rules are skipped, except when the field was already marked as invalid.Set to a Function to decide yourself when to run validation.A boolean true is not a valid value. Example: Disables onblur validation.
$(".selector").validate({
onfocusout: false
});
The callback gets passed two arguments: You can learn details about jQuery Validation from: http://jqueryvalidation.org/ or http://jqueryvalidation.org/documentation/

No comments:

Post a Comment