jQuery验证器插件:验证可选字段 [英] jQuery validator plug-in: validate optional field

查看:20
本文介绍了jQuery验证器插件:验证可选字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题我想使用我创建的自定义验证器验证字段,该验证器本质上是电话号码的正则表达式,仅当该字段具有值时,否则不需要验证,因为它是可选的.

Problem I want to validate a field using a custom validator I've created that's essentially a regex for a phone number only IF the field has a value, otherwise it doesn't need to be validated because it's optional.

自定义验证器:

   $.validator.addMethod('phone', function (value) {
       return /^[01]?[- .]?(?[2-9]d{2})?[- .]?d{3}[- .]?d{4}$/.test(value);
   }, 'Please enter a valid US phone number.');

规则:

 phone: {
  required: true,
  phone: true
 },
 fax: {
  phone: true
 }

我什至尝试过:

 phone: {
  required: true,
  phone: true
 },
 fax: {
  required: function(element){
   if (!$("#cf-fax").val()) { return true; } else { return false; }
  }
  phone: true
 }

作为参考,这是我要参考的字段:

For reference this is the field I'm trying to reference:

<input type="text" name="fax" class="optional" size="15" maxlength="14" id="cf-fax" />

感谢任何帮助,因为我只是迷路了.=

Any help is appreciated because I am just plain lost. =

推荐答案

你可以像这样调用.optional()(在验证插件内部定义)

You can call .optional() (defined inside the validation plugin) like this

$.validator.addMethod('phone', function (value, element) {
   return this.optional(element) || /^[01]?[- .]?(?[2-9]d{2})?[- .]?d{3}[- .]?d{4}$/.test(value);
}, 'Please enter a valid US phone number.');

这是验证插件的标准方案,采取在此处查看他们的其他方法以获取示例.

This is the standard scheme for the validation plugin, take a look at their additional methods here for examples.

这篇关于jQuery验证器插件:验证可选字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆