【问题标题】:jQuery validation plugin - if empty, allow, if not, check required formatjQuery 验证插件 - 如果为空,则允许,如果不是,请检查所需格式
【发布时间】:2015-01-21 10:51:10
【问题描述】:

我有自定义的 jQuery 验证功能,但我无法让它按我想要的方式工作: 如果元素为空,我不想验证它,但如果它不为空,我想检查值是否正确。

我的自定义函数如下所示:

$.validator.addMethod("phoneCZ", function(phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, "");

        if(!phone_number.match(/^((\+420)|(\+421))??[0-9]{3}?[0-9]{3}?[0-9]{3}$/)){ 
            return (phone_number.length < 1);
        }
        else {        
            return (phone_number.length >= 9);
        }
    }, "Neplatné telefonní číslo");

也许只是一些描述: 允许的格式是: 123456789 +420123456789 +421123456789

如果数字格式不正确,我返回true,如果它的长度为0,否则返回false。我的格式匹配,我检查长度是否至少为 9 个字符。

【问题讨论】:

  • 在顶部添加if (phone_number.length === 0) return true;
  • 感谢您的帮助@adeneo

标签: javascript jquery validation


【解决方案1】:

有一个叫做optional的方法可以让你这样做

$.validator.addMethod("phoneCZ", function (phone_number, element) {
    if (this.optional(element)) {
        return true;
    }
    phone_number = phone_number.replace(/\s+/g, "");

    if (!phone_number.match(/^((\+420)|(\+421))??[0-9]{3}?[0-9]{3}?[0-9]{3}$/)) {
        return (phone_number.length < 1);
    } else {
        return (phone_number.length >= 9);
    }
}, "Neplatné telefonní číslo");

演示:

$.validator.addMethod("phoneCZ", function(phone_number, element) {
  if (this.optional(element)) {
    return true;
  }
  phone_number = phone_number.replace(/\s+/g, "");

  if (!phone_number.match(/^((\+420)|(\+421))??[0-9]{3}?[0-9]{3}?[0-9]{3}$/)) {
    return (phone_number.length < 1);
  } else {
    return (phone_number.length >= 9);
  }
}, "Neplatné telefonní číslo");

jQuery(function($) {
  var validator = $('#myform').validate({
    debug: true,
    rules: {
      phoneCZ1: {
        phoneCZ: true
      },
      phoneCZ2: {
        required: true,
        phoneCZ: true
      }
    },
    messages: {}
  });
});
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="myform" method="post" action="">
  <div>
    <input name="phoneCZ1" />
  </div>
  <div>
    <input name="phoneCZ2" />
  </div>
  <input type="submit" value="Save" />
</form>

【讨论】:

  • 谢谢。正是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 1970-01-01
  • 2011-12-11
  • 2011-06-19
  • 2016-12-18
相关资源
最近更新 更多