jQuery jquery验证电话号码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19840301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:42:35  来源:igfitidea点击:

jquery to validate phone number

javascriptjqueryjquery-validate

提问by FlintOff

I want to validate phone numbers like (123) 456-7890 or 1234567890 How should be the 'matches' condition be written in the following code?

我想验证电话号码,如 (123) 456-7890 或 1234567890 应如何在以下代码中写入“匹配”条件?

form.validate({

    rules: {

       phoneNumber: {matches:"[0-9]+",minlength:10, maxlength:10}

回答by Binary Brain

Your regex should be something like

你的正则表达式应该是这样的

[0-9\-\(\)\s]+.

[0-9\-\(\)\s]+.

It matches numbers, dashes, parentheses and space.

它匹配数字、破折号、括号和空格。

If you need something more strict, matching just your example, try this:

如果您需要更严格的内容,仅匹配您的示例,请尝试以下操作:

([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})

([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})

回答by Sparky

Your code:

您的代码:

rules: {
    phoneNumber: {
        matches: "[0-9]+",  // <-- no such method called "matches"!
        minlength:10,
        maxlength:10
    }
}

There is no such callback function, option, method, or rule called matchesanywhere within the jQuery Validate plugin.(EDIT: OP failed to mention that matchesis his custom method.)

在 jQuery Validate 插件中的matches任何地方都没有调用这样的回调函数、选项、方法或规则。编辑:OP 没有提到这matches是他的自定义方法。

However, within the additional-methods.jsfile, there are several phone number validation methods you can use. The one called phoneUSshould satisfy your pattern. Since the rule already validates the length, minlengthand maxlengthare redundantly unnecessary. It's also much more comprehensive in that area codes and prefixes can not start with a 1.

但是,在additional-methods.js文件中,您可以使用多种电话号码验证方法。被调用的那个phoneUS应该满足你的模式。由于规则已经验证的长度,minlength并且maxlength是不必要的冗余。它也更全面,因为区号和前缀不能以1.

rules: {
    phoneNumber: {
        phoneUS: true
    }
}

DEMO: http://jsfiddle.net/eWhkv/

演示:http: //jsfiddle.net/eWhkv/



If, for whatever reason, you just need the regex for use in another method, you can take it from here...

如果出于某种原因,您只需要在另一种方法中使用正则表达式,您可以从这里获取它...

jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.length > 9 && 
    phone_number.match(/^(\+?1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");

回答by FlintOff

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([0-9]{4})/

Supports :

支持:

  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899
  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899

回答by Dishan TD

function validatePhone(txtPhone) {
    var a = document.getElementById(txtPhone).value;
    var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
    if (filter.test(a)) {
        return true;
    }
    else {
        return false;
    }
}

Demohttp://jsfiddle.net/dishantd/JLJMW/496/

演示http://jsfiddle.net/dishantd/JLJMW/496/

回答by thdoan

If you normalize your data first, then you can avoid all the very complex regular expressions required to validate phone numbers. From my experience, complicated regex patterns can have two unwanted side effects: (1) they can have unexpected behavior that would be a pain to debug later, and (2) they can be slower than simpler regex patterns, which may become noticeable when you are executing regex in a loop.

如果首先对数据进行规范化,则可以避免验证电话号码所需的所有非常复杂的正则表达式。根据我的经验,复杂的正则表达式模式可能有两个不需要的副作用:(1) 它们可能有意外的行为,以后调试起来会很痛苦,(2) 它们可能比简单的正则表达式模式慢,当您使用时,这可能会变得明显正在循环中执行正则表达式。

By keeping your regular expressions as simple as possible, you reduce these risks and your code will be easier for others to follow, partly because it will be more predictable. To use your phone number example, first we can normalize the value by stripping out all non-digits like this:

通过使正则表达式尽可能简单,您可以降低这些风险,并且您的代码将更容易被其他人遵循,部分原因是它更具可预测性。以您的电话号码为例,首先我们可以通过像这样去除所有非数字来标准化该值:

value = $.trim(value).replace(/\D/g, '');

value = $.trim(value).replace(/\D/g, '');

Now your regex pattern for a US phone number (or any other locale) can be much simpler:

现在,美国电话号码(或任何其他语言环境)的正则表达式模式可以简单得多:

/^1?\d{10}$/

/^1?\d{10}$/

Not only is the regular expression much simpler, it is also easier to follow what's going on: a value optionally leading with number one (US country code) followed by ten digits. If you want to format the validated value to make it look pretty, then you can use this slightly longer regex pattern:

正则表达式不仅更简单,而且更容易理解正在发生的事情:一个值可选地以第一(美国国家代码)开头,后跟十位数字。如果您想格式化已验证的值以使其看起来漂亮,那么您可以使用这个稍长的正则表达式模式:

/^1?(\d{3})(\d{3})(\d{4})$/

/^1?(\d{3})(\d{3})(\d{4})$/

This means an optional leading number one followed by three digits, another three digits, and ending with four digits. With each group of numbers memorized, you can output it any way you want. Here's a codepen using jQuery Validation to illustrate this for two locales (Singapore and US):

这意味着一个可选的前导数字 1 后跟三位数字,另外三位数字,并以四位数字结尾。记住每组数字后,您可以以任何方式输出。这是一个使用 jQuery 验证的代码笔来说明这两个语言环境(新加坡和美国):

http://codepen.io/thdoan/pen/MaMqvZ

http://codepen.io/thdoan/pen/MaMqvZ

回答by Alfredo González Portero

jQuery.validator.methods.matches = function( value, element, params ) {
    var re = new RegExp(params);
    // window.console.log(re);
    // window.console.log(value);
    // window.console.log(re.test( value ));
    return this.optional( element ) || re.test( value );
}

rules: {
        input_telf: {
            required  : true,
            matches   : "^(\d|\s)+$",
            minlength : 10,
            maxlength : 20
        }
    }

回答by Junior

I know this is an old post, but I thought I would share my solution to help others.

我知道这是一个旧帖子,但我想我会分享我的解决方案来帮助别人。

This function will work if you want to valid 10 digits phone number "US number"

如果您想要有效的 10 位电话号码“美国号码”,此功能将起作用

function getValidNumber(value)
{
    value = $.trim(value).replace(/\D/g, '');

    if (value.substring(0, 1) == '1') {
        value = value.substring(1);
    }

    if (value.length == 10) {

        return value;
    }

    return false;
}

Here how to use this method

这里如何使用这个方法

var num = getValidNumber('(123) 456-7890');
if(num !== false){
     alert('The valid number is: ' + num);
} else {
     alert('The number you passed is not a valid US phone number');
}

回答by vineet

This one is work for me:-

这个对我有用:-

/^\(?(\d{3})\)?[-\. ]?(\d{3})[-\. ]?(\d{4})$/

回答by Pankaj Goel

I tried the below solution and it work fine for me.

我尝试了以下解决方案,对我来说效果很好。

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})([0-9]{4})/

Tried below phone format:

尝试了以下电话格式:

  • +(123) 456 7899
  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899
  • +(123) 456 7899
  • (123) 456 7899
  • (123).456.7899
  • (123)-456-7899
  • 123-456-7899
  • 123 456 7899
  • 1234567899