Validate phone number with JavaScript

前端 未结 26 1617

I found this code in some website, and it works perfectly. It validates that the phone number is in one of these formats:
(123) 456-7890 or 123-

相关标签:
26条回答
  • 2020-11-22 05:37

    /^\+?1?\s*?\(?\d{3}(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$/

    Although this post is an old but want to leave my contribuition. these are accepted: 5555555555 555-555-5555 (555)555-5555 1(555)555-5555 1 555 555 5555 1 555-555-5555 1 (555) 555-5555

    these are not accepted:

    555-5555 -> to accept this use: ^\+?1?\s*?\(?(\d{3})?(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$

    5555555 -> to accept this use: ^\+?1?\s*?\(?(\d{3})?(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$

    1 555)555-5555 123**&!!asdf# 55555555 (6505552368) 2 (757) 622-7382 0 (757) 622-7382 -1 (757) 622-7382 2 757 622-7382 10 (757) 622-7382 27576227382 (275)76227382 2(757)6227382 2(757)622-7382 (555)5(55?)-5555

    this is the code I used:

    function telephoneCheck(str) {
      var patt = new RegExp(/^\+?1?\s*?\(?\d{3}(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$/);
      return patt.test(str);
    }
    
    telephoneCheck("+1 555-555-5555");
    
    0 讨论(0)
  • 2020-11-22 05:37

    Validate phone number + return formatted data

    function validTel(str){
      str = str.replace(/[^0-9]/g, '');
      var l = str.length;
      if(l<10) return ['error', 'Tel number length < 10'];
      
      var tel = '', num = str.substr(-7),
          code = str.substr(-10, 3),
          coCode = '';
      if(l>10) {
        coCode = '+' + str.substr(0, (l-10) );
      }
      tel = coCode +' ('+ code +') '+ num;
      
      return ['succes', tel];
    }
    
    console.log(validTel('+1 [223] 123.45.67'));

    0 讨论(0)
提交回复
热议问题