Validate phone number with JavaScript

前端 未结 26 2241

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

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

提交回复
热议问题