jQuery 验证插件 - 如果为空,则允许,否则,检查所需格式

jQuery validation plugin - if empty, allow, if not, check required format

我有自定义 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

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

有一种叫做 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>