jQuery: The Write Less, Do More JavaScript Library

Plugins/Validation/validate

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Plugins/Validation

validate[options] )

Validates the selected form.
This method sets up event handlers for submit, focus, keyup, blur and click to trigger validation of the entire form or individual elements. Each one can be disabled, see the onxxx options (onsubmit, onfocusout, onkeyup, onclick). focusInvalid focuses elements when submitting a invalid form.

Use the debug option to ease setting up validation rules, it always prevents the default submit, even when script errors occur.

Use submitHandler to implement your own form submit, eg. via Ajax.

Use rules and messages to specify which elements to validate, and how. See rules() for more details about specifying validation rules and the meta option when using the metadata plugin.

Use errorClass, errorElement, wrapper, errorLabelContainer, errorContainer, showErrors, success, errorPlacement, highlight and unhighlight to control how invalid elements and error messages are displayed.

Triggers the following namespaced custom events:

  • invalid-form.validate - Triggered every time an invalid form is submitted
Arguments:
options (Optional)Options
A set of key/value pairs that configure the validate. All options are optional.


Options:



NameType
debugBooleanDefault: false
Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (requires Firebug or Firebug lite). Try to enable when a form is just submitted instead of validation stopping the submit.
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
})

Sets the debug option as the default, handy when validating multiple forms on a single page.

$.validator.setDefaults({
   debug: true
})

submitHandlerCallbackDefault: default (native) form submit
Callback for handling the actual submit when the form is valid. Gets the form as the only argmument. Replaces the default submit. The right place to submit a form via Ajax after it validated.
Submits the form via Ajax when valid.

$(".selector").validate({
   submitHandler: function(form) {
   	$(form).ajaxSubmit();
   }
})

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();
   }
})

ignoreSelector
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.
Ignores all element with the class "ignore" when validating.

$("#myform").validate({
   ignore: ".ignore"
})

rulesOptionsDefault: rules are read from markup (classes, attributes, metadata)
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/metadata rules.
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
     }
   }
})

messagesOptionsDefault: the default message for the method used
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 arugment, it must return a String to display as the message.
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"
     }
   }
})

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!")
     }
   }
})

groupsOptions
Specify grouping of error messages. A group consists of an arbitrary group name as the key and a comma-seperated list of element names as the value. Use errorPlacement to control where the group message is placed.
Use a table layout for the form, placing error messags in the next cell after the input.

$("#myform").validate({
  groups: {
    username: "fname lname"
  },
  errorPlacement: function(error, element) {
     if (element.name == "fname" || element.name == "lname" )
       error.insertAfter("#lastname");
     else
       error.insertAfter(element);
   },
   debug:true
 })

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate({
  groups: {
    username: "fname lname"
  },
  errorPlacement: function(error, element) {
     if (element.name == "fname" || element.name == "lname" )
       error.insertAfter("#lastname");
     else
       error.insertAfter(element);
   },
   debug:true
 })
  });
  </script>
  
</head>
<body>
  <form id="myform">
	<label>Your Name</label>
	<input name="fname" class="required" value="Pete" />
	<input name="lname" id="lastname" class="required" />
	<br/>
	<input type="submit" value="Submit"/>
</form>
</body>
</html>

onsubmitBooleanDefault: true
Validate the form on submit. Set to false to use only other events for validation.
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
})

onfocusoutBooleanDefault: true
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.
Disables onblur validation.

$(".selector").validate({
   onfocusout: false
})

onkeyupBooleanDefault: true
Validate elements on keyup. As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event.
Disables onkeyup validation.

$(".selector").validate({
   onkeyup: false
})

onclickBooleanDefault: true
Validate checkboxes and radio buttons on click.
Disables onclick validation of checkboxes and radio buttons.

$(".selector").validate({
   onclick: false
})

focusInvalidBooleanDefault: true
Focus the last active or first invalid element on submit via validator.focusInvalid(). The last active element is the one that had focus when the form was submitted, avoiding to steal its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off.
Disables focusing of invalid elements.

$(".selector").validate({
   focusInvalid: false
})

focusCleanupBooleanDefault: false
If enabled, removes the errorClass from the invalid elements and hides all errors messages whenever the element is focused. Avoid combination with focusInvalid.
Enables cleanup when focusing elements, removing the error class and hiding error messages when an element is focused.

$(".selector").validate({
   focusCleanup: true
})

metaString
In case you use metadata for other plugins, too, you want to wrap your validation rules into their own object that can be specified via this option.
Tell the validation plugin to look inside a validate-property in metadata for validation rules.

$("#myform").validate({
   meta: "validate",
   submitHandler: function() { alert("Submitted!") }
})

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("#myform").validate({
   meta: "validate",
   submitHandler: function() { alert("Submitted!") }
})
  });
  </script>
  
</head>
<body>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.metadata.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<form id="myform">
  <input type="text" name="email" class="{validate:{ required: true, email:true }}" />
  <br/>
  <input type="submit" value="Submit" />
</form>
</body>
</html>

errorClassStringDefault: "error"
Use this class to create error labels, to look for existing error labels and to add it to invalid elements.
Sets the error class to "invalid".

$(".selector").validate({
   errorClass: "invalid"
})

errorElementStringDefault: "label"
Use this element type to create error messages and to look for existing error messages. The default, "label", has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, no matter the element type).
Sets the error element to "em".

$(".selector").validate({
   errorElement: "em"
})

wrapperString
Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.
Wrap each error element with a list item, useful when using an ordered or unordered list as the error container.

$(".selector").validate({
   wrapper: "li"
})

errorLabelContainerSelector
Hide and show this container when validating.
All error labels are displayed inside an unordered list with the ID "messageBox", as specified by the selector passed as errorContainer option. All error elements are wrapped inside an li element, to create a list of messages.

$("#myform").validate({
   errorLabelContainer: "#messageBox",
   wrapper: "li",
   submitHandler: function() { alert("Submitted!") }
})

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("#myform").validate({
   errorLabelContainer: "#messageBox",
   wrapper: "li",
   submitHandler: function() { alert("Submitted!") }
})
  });
  </script>
  
</head>
<body>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<ul id="messageBox"></ul> 
 <form id="myform" action="/login" method="post"> 
   <label>Firstname</label> 
   <input name="fname" class="required" /> 
   <label>Lastname</label> 
   <input name="lname" title="Your lastname, please!" class="required" /> 
   <br/>
   <input type="submit" value="Submit"/>
 </form>
</body>
</html>

errorContainerSelector
Hide and show this container when validating.
Uses an additonal container for error messages. The elements given as the errorContainer are all shown and hidden when errors occur. But the error labels themselve are added to the element(s) given as errorLabelContainer, here an unordered list. Therefore the error labels are also wrapped into li elements (wrapper option).

$("#myform").validate({
   errorContainer: "#messageBox1, #messageBox2",
   errorLabelContainer: "#messageBox1 ul",
   wrapper: "li", debug:true,
   submitHandler: function() { alert("Submitted!") }
})

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    $("#myform").validate({
   errorContainer: "#messageBox1, #messageBox2",
   errorLabelContainer: "#messageBox1 ul",
   wrapper: "li", debug:true,
   submitHandler: function() { alert("Submitted!") }
})
  });
  </script>
  <style>#messageBox1, #messageBox2 { display: none }</style>
</head>
<body>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<div id="messageBox1"> 
  <ul></ul> 
</div> 
<form id="myform" action="/login" method="post"> 
  <label>Firstname</label> 
  <input name="fname" class="required" /> 
  <label>Lastname</label> 
  <input name="lname" title="Your lastname, please!" class="required" />
  <br/>
  <input type="submit" value="Submit"/>
</form> 
<div id="messageBox2"> 
  <h3>There are errors in your form, see details above!</h3> 
</div>
</body>
</html>

showErrorsCallbackDefault: None, uses built-in message disply.
A custom message display handler. Gets the map of errors as the first argument and and array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors().
Update the number of invalid elements each time an error is displayed. Delegates to the default implementation for the actual error display.

$(".selector").validate({
   showErrors: function(errorMap, errorList) {
		$("#summary").html("Your form contains " + this.numberOfInvalids() + " errors, see details below.");
		this.defaultShowErrors();
	}
 })

errorPlacementCallbackDefault: Places the error label after the invalid element
Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object.
Use a table layout for the form, placing error messags in the next cell after the input.

$("#myform").validate({
  errorPlacement: function(error, element) {
     error.appendTo( element.parent("td").next("td") );
   },
   debug:true
 })

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate({
  errorPlacement: function(error, element) {
     error.appendTo( element.parent("td").next("td") );
   },
   debug:true
 })
  });
  </script>
  
</head>
<body>
  <form id="myform" action="/login" method="post">
	<table>
		<tr>
			<td><label>Firstname</label>
			<td><input name="fname" class="required" value="Pete" /></td>
			<td></td>
		</tr>
		<tr>
			<td><label>Lastname</label></td>
			<td><input name="lname" title="Your lastname, please!" class="required" /></td>
			<td></td>
		</tr>
		<tr>
			<td></td><td><input type="submit" value="Submit"/></td><td></td>
	</table>
</form>
</body>
</html>

successString, Callback
If specified, the error label is displayed to show a valid element. If a String is given, its added as a class to the label. If a Function is given, its called with the label (as a jQuery object) as its only argument. That can be used to add a text like "ok!".
Add a class "valid" to valid elements, styled via CSS.

$("#myform").validate({
   success: "valid",
   submitHandler: function() { alert("Submitted!") }
})

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate({
   success: "valid",
   submitHandler: function() { alert("Submitted!") }
})
  });
  </script>
  <style>label.valid {
	background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
	height:16px;
	width:16px;
	display: block;
	position: absolute;
	top: 4px;
	left: 152px;
}</style>
</head>
<body>
  
<form id="myform">
  <input type="text" name="email" class="required" />
  <br/>
  <input type="submit" value="Submit" />
</form>
</body>
</html>

Add a class "valid" to valid elements, styled via CSS, and add the text "Ok!".

$("#myform").validate({
   success: function(label) {
     label.addClass("valid").text("Ok!")
   },
   submitHandler: function() { alert("Submitted!") }
})

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
  <script>
  $(document).ready(function(){
    $("#myform").validate({
   success: function(label) {
     label.addClass("valid").text("Ok!")
   },
   submitHandler: function() { alert("Submitted!") }
})
  });
  </script>
  <style>label.valid {
	background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
	height:16px;
	width:16px;
	display: block;
	position: absolute;
	top: 4px;
	left: 152px;
	padding-left: 18px;
}</style>
</head>
<body>
  
<form id="myform">
  <input type="text" name="email" class="required" />
  <br/>
  <input type="submit" value="Submit" />
</form>
</body>
</html>

highlightCallbackDefault: Adds errorClass (see the option) to the element
How to highlight invalid fields. Override to decide which fields and how to highlight.
Highlights an invalid element by fading it out and in again.

$(".selector").validate({
  highlight: function(element, errorClass) {
     $(element).fadeOut(function() {
       $(element).fadeIn()
     })
  }
})

Adds the error class to both the invalid element and it's label

$(".selector").validate({
  highlight: function(element, errorClass) {
     $(element).addClass(errorClass);
     $(element.form).find("label[for=" + element.id + "]").addClass(errorClass);
  },
  unhighlight: function(element, errorClass) {
     $(element).removeClass(errorClass);
     $(element.form).find("label[for=" + element.id + "]").removeClass(errorClass);
  }
});

unhighlightCallbackDefault: Removes the errorClass
Called to revert changes made by option highlight, same arguments as highlight.