简体   繁体   English

jquery验证电话号码

[英]jquery to validate phone number

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}

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})

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 matches anywhere within the jQuery Validate plugin . 在 jQuery Validate 插件matches任何地方都没有这样的回调函数、选项、方法或规则称为matches ( EDIT: OP failed to mention that matches is his custom method. ) 编辑:OP 没有提到matches是他的自定义方法。

However, within the additional-methods.js file , there are several phone number validation methods you can use.但是,在additional-methods.js文件中,您可以使用多种电话号码验证方法。 The one called phoneUS should satisfy your pattern.一个叫phoneUS应该满足你的模式。 Since the rule already validates the length, minlength and maxlength are redundantly unnecessary.由于规则已经验证了长度,因此minlengthmaxlength是多余的。 It's also much more comprehensive in that area codes and prefixes can not start with a 1 .它也更全面,因为区号和前缀不能以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");
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;
    }
}

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

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

Supports :支持:

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

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, '');

Now your regex pattern for a US phone number (or any other locale) can be much simpler:现在,美国电话号码(或任何其他语言环境)的正则表达式模式可以简单得多:

/^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})$/

This means an optional leading number one followed by three digits, another three digits, and ending with four digits.这意味着一个可选的前导数字 1 后跟三位数字,另外三位数字,并以四位数字结尾。 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):这是一个使用 jQuery 验证的代码笔来说明这两个语言环境(新加坡和美国):

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

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
        }
    }

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');
}

这个对我有用:-

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

I tried the below solution and it work fine for me.我尝试了以下解决方案,对我来说效果很好。

/\(?([0-9]{3})\)?([ .-]?)([0-9]{3})\2([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
  • (123)-456-7899 (123)-456-7899
  • 123-456-7899 123-456-7899
  • 123 456 7899 123 456 7899
  • 1234567899 1234567899

您知道这个世界上有很多电话号码格式,因此您可以使用此正则表达式来验证任何电话号码^[0-9-+s()]*$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM