jQuery validation of NANP Phone numbers

烈酒焚心 提交于 2019-12-06 09:59:20

The problem with your code is that regex1 is looking for special characters in the phone string. The code fails because you are stripping all special characters from the phone string in the line phone = phone.replace(/[^0-9]/g,'');, and thus when you do your test against regex1 you are looking for values that you already removed.

By all means, your approach is fine. Often I find it easier to use two simple REGEXs instead of trying to fit everything into one catch-all REGEX. Once you modify regex1 to only do a NANP validity check on a 10 digit number with no special characters, your code will work fine.

function validatePhone(){
    var error = 1;

    var hasError = false;
    var $this = $(this);
    var regex1 = /^([2-9]{1}\d{2})([2-9]{1}\d{2})\d{4}$/;

    phone = $(this).val();
    phone = phone.replace(/[^0-9]/g,'');        
    if(!regex1.test(phone)){
        hasError = true;
        $this.css('background-color','#FFEDEF');
    }   
    else{
        area = phone.substring(0,3);
        prefix = phone.substring(3,6);
        line = phone.substring(6);
        $this.val('(' + area + ') ' + prefix + '-' + line);
        $this.css('background-color','#FFFFFF');    
    }

Here is my not very strict but yet nice RegExp:

/^\D*([2-9]\d{2}\D*){2}(\d{2}\D*){2}\D*$/

It accepts:

  • (235)-546-42-09
  • 452-845-12-12
  • [933]-323-34-53
  • 222-435-0903
  • 222-4350903
  • 2224350903
  • ( 222 ) -- 785 -- 12 -- 76

It doesn't accepts:

  • 111-342-45-45
  • 234-111-50-78
  • 222-222-222-2 (you may simply modify RegExp to remove this)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!