Validate phone number with JavaScript

前端 未结 26 2151

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");
    

提交回复
热议问题