Have you ever wanted to show one error message at a time, or create a different type of visual queue for a specific invalid element on a form? Using the
validate options, you can easily create any effect you want.
The example below, is designed to show the first error message in a form and to set focus on that first element. The message is displayed in a basic JavaScript alert box, not very elegant but it makes for a simple demo.
<title>Show JS Alert - First Validation Error</title> |
<script src="Scripts/jquery-1.4.2.js" type="text/javascript"></script> |
<script src="Scripts/jquery.validate.js" type="text/javascript"></script> |
<script type="text/javascript"> |
$(document).ready(function() { |
invalidHandler: function(form, validator) { |
var errors = validator.numberOfInvalids(); |
alert(validator.errorList[0].message); |
validator.errorList[0].element.focus(); |
TextBox1: { required: true, minlength: 2 }, |
TextBox2: { required: true, minlength: 2 }, |
TextBox3: { required: true, minlength: 2 } |
TextBox1: { required: "TextBox1 Required", minlength: "TextBox1 MinLength" }, |
TextBox2: { required: "TextBox2 Required", minlength: "TextBox2 MinLength" }, |
TextBox3: { required: "TextBox3 Required", minlength: "TextBox3 MinLength" } |
errorPlacement: function(error, element) { |
// Override error placement to not show error messages beside elements // |
label { width: 90px; display: block; float: left; } |
ul li { line-height: 1.8; } |
<form id="elForm" action="#"> |
<h1>jQuery Validation - Show First Error Only</h1> |
<li><label>Text Box 1</label><input type="text" name="TextBox1" id="TextBox1" value="" /></li> |
<li><label>Text Box 2</label><input type="text" name="TextBox2" id="TextBox2" value="" /></li> |
<li><label>Text Box 3</label><input type="text" name="TextBox3" id="TextBox3" value="" /></li> |
<input type="submit" id="submit" value="Validate" /> |
Here are the important parts to focus on.
1. invalidHandler, this option give you access to the current validator and all the errors messages/items via the “validator.errorlist”.
invalidHandler: function(form, validator) { |
var errors = validator.numberOfInvalids(); |
alert(validator.errorList[0].message); |
validator.errorList[0].element.focus(); |
2. errorPlacement, this function controls how error messages are displayed. Since we don’t want any error messages displayed by default, we can override the default errorPlacement with a empty method call.
errorPlacement: function(error, element) { |
The end result is a alert box showing the first broken rule for the first invalid element on the page. In the example each input has 2 rules (required and minLength), if you enter a single character into the first text box the message will change from “TextBox1 Required” to “TextBox1 MinLength”.
No comments:
Post a Comment