简体   繁体   中英

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?

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.

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}$/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM