Skip to content
Advertisement

Regex for Phone Number validation in JavaScript [closed]

I am validate Phone Number. I would like to allow only (123) 123-1234. But my code is also allowing 123 123-1234. My Regex is like below.

var format = /^(?([0-9]{3}))?[ ]?([0-9]{3})[-]?([0-9]{4})$/;

Where is my mistake ?

Advertisement

Answer

You have a ? quantifier for ( and ) in your regex, which matches your parentheses for zero or one times. Simply removing it will do the trick.

var format = /^(([0-9]{3}))[ ]?([0-9]{3})[-]?([0-9]{4})$/;

Have a test for it here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement