Validating Phone Numbers Using Javascript

前端 未结 9 2233
刺人心
刺人心 2021-01-06 00:41

I\'m working on a web form with several fields and a submit button. When the button is clicked, I have to verify that the required text boxes have been filled in and that th

9条回答
  •  醉酒成梦
    2021-01-06 00:53

    As for your regexp I guess it should be

    ^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}
    

    But in general the presumption is not correct because one might enter something like ++44 20 1234 56789 or +44 (0) 1234 567890 it is better to do something like this

    var phone = document.forms["myForm"]["phone"].value;
    var phoneNum = phone.replace(/[^\d]/g, '');
    if(phoneNum.length > 6 && phoneNum.length < 11) {  return true;  }
    

    this will assure that entered value has 7 to 10 figures nevertheless what the formatting is. But you have to think about max length for number might be more than 10 as in the sample above.

提交回复
热议问题