jquery validate验证规则重用
来源:互联网 发布:李鸿章 袁世凯 知乎 编辑:程序博客网 时间:2024/04/28 18:08
当多个控件验证规则相同时,如何避免冗余代码并应用相同规则呢?
【1st way. addMethod+addClassRules】
场景:维护学生档案时需要维护父母、监护人、紧急联系人的身份证号码,此时页面4个input都需要身份证号码验证;
解决:
[1].在四个input的class上增加idcard;
[2].定义验证规则idCard,对样式为idcard的控件附加身份证验证;
$.validator.addMethod("idCard", $.validator.methods.card, "身份证号不正确");
$.validator.addClassRules("idcard", {idCard : true});
参考自动动我试试:
Refactoring rules
Whenever you have multiple fields with the same rules and messages, refactoring those can reduce a lot of duplication. Using addMethod and addClassRules are most effective for that.
Let's consider an example where you have ten customer fields, each required and with a minlength of 2. You need custom messages for both rules. To avoid having to specify those rules and messages again and again, we can alias existing methods with different messages and group them into a single class:
// alias required to cRequired with new message$.validator.addMethod("cRequired", $.validator.methods.required, "Customer name required");// alias minlength, too$.validator.addMethod("cMinlength", $.validator.methods.minlength,// leverage parameter replacement for minlength, {0} gets replaced with 2$.validator.format("Customer name must have at least {0} characters"));// combine them both, including the parameter for minlength$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });
With that in place, we can add a class customer to all customer fields and be done with it:
<input name="customer1" class="customer"> <input name="customer2" class="customer"> <input name="customer3" class="customer">
You can also reuse existing methods inside other custom methods, to reuse certain implementations. For example, if you're writing a custom method for validating email addresses inside a single field, you could call the existing email method for each email:
jQuery.validator.methods.email.call(this, email, element)
- jquery validate验证规则重用
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- JQuery validate验证规则
- jquery validate 验证规则扩展
- jquery validate 动态增加删除验证规则
- jquery插件validate内置验证规则
- jquery validate 动态增加删除验证规则
- Jquery validate插件自定义验证规则
- JQuery validate 各项验证规则讲解
- jquery validate添加自定义验证规则(验证邮箱 邮政编码)
- UML类图几种关系的总结
- redo log处理
- javascript学习记录
- html响应式布局
- Servlet
- jquery validate验证规则重用
- libevent的一个bug
- c#,保存图像为Icon
- javaScript与Objective-C交互
- 教你搞定Android自定义ViewGroup
- 浅谈UML的概念和模型之UML九种图
- Activity的四种启动模式详解
- HTML总结
- NSString的详细用法(函数说明)