1

The following formats are allowed for the phone number

  1. xxx-xxx-xxxx [x represents a digit]
  2. xxx.xxx.xxxx
  3. xxxxxxxxxx [digit ten times]

I have the working sample for the formats but I am unable to combine them in a single regex. How to combine them into a single regex?

  1. "/^[1-9]\d{2}-\d{3}-\d{4}|^\d{10}$/"
  2. "/^[1-9]\d{2}[.]\d{3}[.]\d{4}|^\d{10}$/"
  3. "/^\d{10}$/"

My regex code in angular:

<div class="form-group" ng-class="{'has-error':userprofileForm.phone.$touched && userprofileForm.phone.$invalid && userprofileForm.extension.$touched && userprofileForm.extension.$invalid}">
   <label for="profile-phone" class="control-label">{{'PHONE'|translate }}</label>
    <div>
       <input name="phone" type="text" class="form-control" ng-model="userprofile.phoneNumber" ng-pattern="/^\d{10}$/" required="required" />
       <div ng-show="userprofileForm.phone.$touched && userprofileForm.phone.$invalid">    
          <span ng-message="required">Please enter phone number</span>
        </div>
    </div>
</div>

2 Answers 2

2

You can combine them like so:

ng-pattern="/^([1-9]\d{2}-\d{3}-\d{4})|([1-9]\d{2}\.\d{3}\.\d{4})|(\d{10})$/"

Just put every pattern in its own group with () and or them together with |.

Or more compact using a back reference (assuming your third case should also not start with a 0):

 ng-pattern="/^[1-9]\d{2}([.-]?)\d{3}\1\d{4}$/"

RegEx breakdown:

^       // start of line
[1-9]   // match '1', '2', '3', '4', '5', '6', '7', '8' or '9'
\d{2)   // match 2 digits
(       // begin capturing group 1
[.-]    // match '.' or '-' 
?       // make the preceeding [.-] optional, so capturing group 1 matches '.', '-' or nothing. 
)       // end capturing group 1
\d{3)   // match 3 digits
\1      // back reference: match what was matched by capturing group 1
\d{4)   // match 4 digits 
$       // match end of line

Note that due to the use of the back reference a mix like xxx.xxx-xxxx is correctly rejected.

Sign up to request clarification or add additional context in comments.

3 Comments

[1-9] is not \d. +1 for using a back reference.
catch ="/^[1-9]\d{2}([.-]?)\d{3}\1\d{4}$/" makes this combination valid xxx.xxx-xxxx which should not be the case.
@arvind: xxx.xxx-xxxx is invalid: /^[1-9]\d{2}([.-]?)\d{3}\1\d{4}$/.test('123.456-7890') returns false. Note that the \1 is a back reference to the first capturing group, so has to mach what was matched by ([.-]?). Explanatory RegEx breakdown added to answer.
1

Here's a similar post with various answers including $filter, regex etc. Do check it out..

Also this handy online regex validator explains your regex might help validate the syntax.

Hope this helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.