当多个控件验证规则相同时,如何避免冗余代码并应用相同规则呢?

【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)

最新文章

  1. Cygwin/babun install telnet
  2. 升级OpenSSh到 7.3p1
  3. java删除文件
  4. java一点小的知识点
  5. 使用putty组件向服务器上传或下载文件
  6. Spring Boot中使用Swagger2构建强大的RESTful API文档
  7. ajax请求跨域问题
  8. Zabbix利用msmtp+mutt发送邮件报警(公告:这文章有问题,还没有修改,2016-08-25)
  9. Oracle EBS-SQL (MRP-2):检查期间主计划录入记录数.sql
  10. GRPC: set up..
  11. 整理 logging 2种方式
  12. ELK Packetbeat 部署指南
  13. [skill] 补码
  14. 20180307-Xen、KVM、VMware、hyper-v等虚拟化技术的比较
  15. POJ 1509 Glass Beads---最小表示法
  16. FFT(快速傅里叶变换)算法详解
  17. .NET:如何实现 “热插拔”?
  18. 【Echo】实验 -- 实现 C/C++下TCP, 服务器/客户端 通讯
  19. [翻译]Review——How JavaScript works:The building blocks of Web Workers
  20. sh: 1: node: Permission denied

热门文章

  1. git使用(公钥私钥产生--远程库添加公钥--本地库关联远程库-使用)
  2. 图论之tarjan缩点
  3. .net core @Html 自定义属性中包含特殊符号解决
  4. c#邮件发送服务
  5. mysql读写分离原理及配置
  6. 如何把非服务程序(一般的应用程序)注册为Windows服务
  7. POJ 1064 Cable master 【二分答案】
  8. swift语言点评十一-Methods
  9. swift语言点评五-Function
  10. CentOS 6.9 CentOS 7.4 自动安装系统 kickstart