Regex for Phone Number validation in JavaScript

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 ?


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

Leave a Reply

Your email address will not be published. Required fields are marked *