Norbert Nagy
Norbert Nagy

Reputation: 142

Validate phone number with a regex filter in javascript

I'm learning how to use regex filters in Javascript and I have this filter now:

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

This should check my telephone number input to make sure that it is entered in the following format:

xx-xxx-xxxx-xxx with the x representing numbers from 0-9 and the minus signs in between.

My problem is that even if the minus signs are left out the filter still validates the field.

Can someone explain me how to make sure that the field only validates when the minus signs are entered?

Upvotes: 1

Views: 2447

Answers (3)

hwnd
hwnd

Reputation: 70732

The ? makes the preceding token optional, meaning between "zero or one" time. If you're wanting to only validate when the hyphens are entered, you need to remove the optional quantifier.

You could simply write the following to validate that format:

var phonenoFilter = /^\d{2}-\d{3}-\d{4}-\d{3}$/

Upvotes: 1

Eder
Eder

Reputation: 1884

Try the following pattern, each number field has its own capturing group leaving the - characters out.

/^(?:(\d{2})\-)?(\d{3})\-(\d{4})\-(\d{3})$/

Eg:

match[0] -> xx
match[1] -> xxx
match[2] -> xxxxx
match[3] -> xxx

Upvotes: 0

ShaneQful
ShaneQful

Reputation: 2236

If you don't mind me saying your regex is a little more complex than it needs to be this would work and be a little easier to understand:

\d{2}-\d{3}-\d{4}-\d{3}

That said in relation to your question, it is the ? mark in your regex which is making the dashes optional.

Upvotes: 3

Related Questions