2
votes

I'm trying to get a regex that will validate the following formats:

234-567-8901
1-234-567-8901

I have tried various examples, but not sure how to get the one that will take into account the possible 1- at the begging and still inforce the 234-567-8901.

Rules are, any digit, 2 or 3 dashes, if 3 dashes then 11 numberes, if 2 dashes then 10 numbers.

^[0-9-]*$
^[\d-]+$
^[\d-]+$
2
which language? which framework? use ready-to-use parsers - gaussblurinc

2 Answers

15
votes

You can use:

^(1-)?\d{3}-\d{3}-\d{4}$

RegEx Details:

  • ^: Start
  • (1-)?: Match optional 1- at the start
  • \d{3}-\d{3}-\d{4}: Match phone no string of 10 digits with hyphens after 3rd and 6th digits
  • $: End
0
votes
 telephone: function (val, field) {
    return /^(\d{3}[-]?){1,2}(\d{4})$/.test(val);
},
telephoneText: "Invalid phone number",
telephoneMask: /[\d-]/

Check out https://regex101.com/ to test your regex.