How to apply Multiple ng-pattern with one input control


I am trying to Validate Postal code and Phone Number in Text box using Angularjs. But it's not working

 <input type="text" class="form-control errorfields" id="postalCode"
 name="postalCode" ng-model="postalCode" 
  ?\d[A-CEGHJ-NPRSTV-Z]\d)$)||(^[0-9])/"  required>
Problem courtesy of: Ashu


First, having double pipes in your regex syntax as mico pointed out, is invalid and will break your expression.

Second, ng-pattern can only validate one pattern per input. If you need it to validate either or, you will need to go one of two routes, create a custom directive, or add some logic to the controller to determine which expression we should check against and pass it into ng-pattern using data binding. This is bad practice in the angular world, so your best bet is to make a directive.

Solution courtesy of: richbai90


Your regex has two || instead of single, which breaks the regex validation clause.

I pasted it to ( and it says that char breaks it.

Discussion courtesy of: mico

I think you need to wrap a ng-form around your input. And then you can use [formName].postalCode.$error

Discussion courtesy of: Qi Tang

See this answer: Angularjs dynamic ng-pattern validation

You can add a function from scope that returns a true or false based on the validation test. Here is some code below to check out. See the answer for additional information:


$scope.postalCodeValidation = (function() {
    var regexp = /^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/;
    return {
        test: function(value) {
            return regexp.test(value);


<input type="text" class="form-control errorfields" id="postalCode"
 name="postalCode" ng-model="postalCode" 
 ng-pattern="postalCodeValidation "  required>
Discussion courtesy of: Brian Gerhards

This recipe can be found in it's original form on Stack Over Flow.