【问题标题】:jQuery custom validation: phone number starting with 6jQuery自定义验证:以6开头的电话号码
【发布时间】:2011-05-28 07:09:40
【问题描述】:

我有一个表单,您必须在其中输入您的电话号码和其他字段。

我正在使用 jQuery Validate 验证表单。

验证电话号码字段:

rules: {
    phone: {
    required: true,
        minlength: 9,
        number:true
    },..

但我还需要检查电话是否以 6 开头。

我该怎么做?

【问题讨论】:

  • "by" => "with",仅供参考:"电话号码以 with 6 开头"
  • 哎呀,谢谢,非常急于拼写:)
  • @user:不只是你,我看到了很多很多。 :-) 我见过“如何用 Y 替换 X?”的次数......我认为有一种广泛使用的语言,在这种情况下使用“by”的类比,人们翻译翻译得太字面意思了。这是非常可以原谅的。 :-)

标签: jquery jquery-validate phone-number


【解决方案1】:

您可以添加自定义验证器

jQuery.validator.addMethod("phoneStartingWith6", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
    return this.optional(element) || phone_number.match(/^6\d{8,}$/);
}, "Phone number should start with 6");

并像这样使用它:

rules: {
    phone: {
        required: true,
        minlength: 9,
        phoneEnding6: true
    },..

您需要编辑phone_number.match 中的正则表达式以满足您的要求。

【讨论】:

  • 如果它解决了您的问题,您可以通过单击左侧的大复选框来接受它作为答案(除非您期待更好的答案)。 :)
  • 这很好用,除了方法名称有误导性。应该是phoneStarting6 吗?
【解决方案2】:

我认为您需要添加一个自定义验证器。

$.validator.addMethod("phoneNumber", function(uid, element) {
    return (this.optional(element) || uid.match(phone number regex));
}

【讨论】:

    【解决方案3】:

    你也可以试试简单的Javascript函数

    "Hello World!".startsWith("He"); //true
    

    注意:此评论/代码适用于不使用 jquery validate 的人。

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多