jQuery Validation Plugin
使用方式很简单,简单测试代码如下:
<html> <head> <script type="text/javascript" src="./jquery-1.7.2.js"></script> <script type="text/javascript" src="./jquery.validate.1.11.js"></script> </head> <body> <form id="myform"> <fieldset> <input type="text" required="required" name="description" id="description"> <button type="submit">Check</button> </fieldset> </form> <script>window.onload = function() { // just for the demos, avoids form submit jQuery.validator.setDefaults({ debug: true, success: "valid" }); $( "#myform" ).validate({ rules: { description: { required: true, maxlength: 4 } } }); };</script> </body> </html>
如果希望自定义提示信息的位置,使用errorPlacement参数,修改后,代码如下:
<html> <head> <script type="text/javascript" src="./jquery-1.7.2.js"></script> <script type="text/javascript" src="./jquery.validate.1.11.js"></script> </head> <body> <form id="myform"> <fieldset> <input type="text" required="required" name="description" id="description"> <button type="submit">Check</button> </fieldset> </form> <script>window.onload = function() { // just for the demos, avoids form submit jQuery.validator.setDefaults({ debug: true, success: "valid" }); $( "#myform" ).validate({ errorPlacement: function(error, element) { if (element.is(":radio")) error.appendTo(element.parent()); else error.insertAfter(element); }, rules: { description: { required: true, maxlength: 4 } } }); };</script> </body> </html>
其中errorPlacement中如果添加了修改,则需要if/else完整语句,因jquery.validation.js源码中,如果判断到已设置errorPlacement则按照其配置方式来处理。
所以,如果仅在errorPlacement中增加的if语句,而没有对其他条件(else)处理,则仅当满足if条件时显示提示信息,其他无法显示提示信息。
showLabel: function(element, message) {
//......
701 if ( this.settings.errorPlacement ) {
702 this.settings.errorPlacement(label, $(element) );
703 } else {
704 label.insertAfter(element);
705 }
//.....
}
Refs:
[2] 官网文档
http://www.iteye.com/problems/85374