Validate phone number with JavaScript

前端 未结 26 2120

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:12

    I would suggest using something clearer (especially thinking to who will have to maintain the code)... what about:

    var formats = "(999)999-9999|999-999-9999|9999999999";
    var r = RegExp("^(" +
                   formats
                     .replace(/([\(\)])/g, "\\$1")
                     .replace(/9/g,"\\d") +
                   ")$");
    

    where the regexp is built from a clear template ? Adding a new one would then be a no-brainer and may be even the customer itself could be able to do that in a "options" page.

提交回复
热议问题