2

I want to use regular expression in AngularJs that accept this three statement :

09344542525 -> 11 length integer that start with 09

02144532363 -> 11 length integer that start with 021

44532363 -> 8 length integer

Here is my HTML :

<div class="container co-operate" ng-controller="cooperationController">
    <form novalidate name="cooperationForm" class="signinform">
        <div class="form-group inner-addon right-inner-addon">
            <label class="form-label control-label"></label>
            <input ng-model="restaurantInformation.tel" type="text" name="tel" id="tel" placeholder="phone number"
               ng-pattern="mobRegEx || prePhoneRegEx || phoneRegEx" class="form-control default-input singleline-input" required />
            <span class="form-icon icon icon-avatar"></span>
        </div>
        <p ng-show="cooperationForm.tel.$error.pattern" style="color: red">Wrong number format</p>
    </form>
</div>

Angular:

app.controller('cooperationController', function ($scope) {
    $scope.mobRegEx = '/09[0-3][0-9]{8}/';
    $scope.prePhoneRegEx = '/021[0-9]{8}/';
    $scope.phoneRegEx = '[0-9]{8}';
    .
    .
    .
}

Actually , when my input is dirty and I test integer, error paragraph is always show error.

Any suggestion to modify regular expression?

3 Answers 3

3

All 3 combined:

/^(?:0(?:21|9[0-9]))?[0-9]{8}$/

Description

  • ^ matches the beginning of string
  • (?:..)? is an optional group matching
    • 0(?:21|9[0-9]) literal 021 OR...
    • 09 and another digit
  • [0-9]{8} 8 more digits
  • $ matching the end of string as well.

Notice I added ^ and $ anchors to avoid matching a substring

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

Comments

0

You're trying to use multiple regular expressions in ng-pattern by separating them using pipes - that's not valid. As suggested in the answer here you should implement a custom directive (ng-phone-number?) or combine your multiple expressions into a single pattern.

Using a directive will probably be the most maintainable approach.

2 Comments

I've completed my question.
My answer still stands; implement a custom directive that tests the inputs against any of the regex patterns.
0

var regExp = /(+09|021|44532363)\d{1,12}/g; var result = string.match(regExp); console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.