如何使用 jQuery 验证以准确的澳大利亚格式验证输入字段 phone?

How to validate input field phone with accurate Australian format using jQuery Validation?

我正在尝试输入 (phone) 字段,该字段不是必填字段,但已根据澳大利亚 phone 号码进行了验证。

        <div>
            <label for="contactPhone">Your Phone: </label>
            <input type="phone" class="form-control eform__phone"
                   id="contactPhone" name="phone"
                   placeholder="e.g. 04000000000">
        </div>

JavaScript:

  /**
   * validate phone number according to australian format
   * Ref: https://ilikekillnerds.com/2014/08/regular-expression-for-validating-australian-phone-numbers-including-landline-and-mobile/
   */
  jQuery.validator.addMethod("phoneAU", function(value, element) {
    var phoneExpression = /^\({0,1}((0|\+61)(2|4|3|7|8)){0,1}\){0,1}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{2}(\ |-){0,1}[0-9]{1}(\ |-){0,1}[0-9]{3}$/;

    if (value.match(phoneExpression)) {
      return true;
    }
    return false;
  }, jQuery.validator.messages.phoneAU || "Please specify a valid phone number");

然后在验证规则函数中使用了以下内容

   phone: {
     phoneAU: true
   },

我正在使用 jQuery 验证。但是,它正在根据需要进行考虑。我不希望它是必需的。我只是想确保每当用户填写它时,他们都会用 phone 数字的正确澳大利亚格式填写它。

只需将您的 "validated" 条件更改为:

if (value.length === 0 || value.match(phoneExpression)) {
  return true;
}

编辑:查看@Sparky 的回答以获得更多optimal/appropriate 解决方案。

先前接受的答案不是处理这种情况的正常方法。为了保留使用自定义规则的能力,而不是强制使用,请使用 "OR" this.optional(element) 作为条件的一部分,这就是插件中默认规则的构造方式。

if (this.optional(element) || value.match(phoneExpression)) {
  return true;
}
return false;

或者只是这一行 shorthand 版本...

return this.optional(element) || value.match(phoneExpression);