DEV Community

Discussion on: RegEx in JavaScript with a cool project 🔥

lukeshiru profile image
LUKESHIRU • Edited on

I believe you can have a validation for all those formats in a single RegExp that would look something like this:

/^(1 )*\(*\d{3}([ \-\)] ?)?\d{3}[ \-]?\d{4}/
Enter fullscreen mode Exit fullscreen mode

Maybe I'm missing some case, but afaik that single expressing matches all your examples.


Edit: Yup, it works

jaspalsingh1998 profile image
Jaspal Singh Author

Thank For sharing this regex pattern with us 😅🔥

fjones profile image
FJones • Edited on

It also incorrectly matches:

  1. Multiple opening ( e.g. ((555) 555-5555
  2. Mismatched () e.g. (555 555-5555
  3. Multiple leading 1 e.g. 1 1 555 555-5555

It's important to consider both positive and negative constraints for the resulting regular language.

This should be a bit closer, but also not entirely accurate for certain edge cases:

/^(1 )?(\d{3}|\(\d{3}\))[ -]?\d{3}[ -]?\d{4}/
Enter fullscreen mode Exit fullscreen mode