afn afn - 4 months ago 8
Javascript Question

Regular expression for numbers in AngularJs

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?

Answer

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