Validate phone number with JavaScript

前端 未结 26 2148

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

    This will work:

    /^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
    

    The ? character signifies that the preceding group should be matched zero or one times. The group (-|\s) will match either a - or a | character. Adding ? after the second occurrence of this group in your regex allows you to match a sequence of 10 consecutive digits.

提交回复
热议问题