简体   繁体   中英

Regex - Validate Mobile Phone with Optional Country Code

I'm currently studying regular expression. I didn't really know / understand how to write an expression with 2 condition. Or do I have to write 2 regex for each case?

What I am on is,

I have a txtMobile field in my html field

<label for="txtMobile">Mobile:*</label>
<input id="txtMobile" type="text" name="txtMobile" size="22" maxlength="22">

In my javascript file I'm trying to create a expressions with the following rule

Format: (+##)###-###-####/#### extension is optional and it may start without country code.

Is there any way to do in a single expression or do I have to type if conditions for each case in my javascript file?

Here is what I did /^([0-9]{3})\\-([0-9]{3})\\-([0-9]{4})\\/([0-9]{4})$/

Make the groups optional by using ? which means "zero or one of the preceding":

/^([0-9]{3}-)?([0-9]{3})\-([0-9]{4})(\/[0-9]{4})?$/

? is a modifier like * (zero or more of the preceding) and + (one or more of the preceding).

This makes both groups optional which means that numbers with all three components (country code, number, extension), numbers with either of the optional components (number + extension, country code + number), and numbers with neither of the optional components, will be accepted by the regex.

EDIT

Your mistake in the regex in your comment is that the ? is after the escaped ) , which means zero or one of an actual ) and not of a group. What you need is:

^(\(\+[0-9]{2}\))?([0-9]{3}-)?([0-9]{3})\-([0-9]{4})(\/[0-9]{4})?$

Use ? to indicate an optional atom.

/^(\(+[0-9]{2}\))?...

Here I have made the preceding group optional, and notice how the parentheses group several atoms into a single atom. The literal parentheses are escaped. The is the start of a regex that allows an optional country code following your format. Allowing for an optional extension is left as an exercise to the reader. :)

Like the other guys said ? matches 0 or 1 of the proceeding token.

/^(\(\+\d{1,3}\))?(\d{3}-){2}\d{4}(\/\d{3,4})?$/

Matches:

999-999-9999
(+1)999-999-9999
(+11)999-999-9999
(+111)999-999-9999
999-999-9999/000
(+1)999-999-9999/000
(+11)999-999-9999/000
(+111)999-999-9999/000
999-999-9999/0000
(+1)999-999-9999/0000
(+11)999-999-9999/0000
(+111)999-999-9999/0000

I like to use this tool: http://gskinner.com/RegExr/

It implements Flash's version of RegEx, which is not perfectly identical to Javascript. But it's close enough for most work. If someone else can suggest a JS RegEx tool, even better.

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