Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply Multiple ng-pattern with one input control

Tags:

angularjs

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" 
 ng-pattern="/(^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z]
  ?\d[A-CEGHJ-NPRSTV-Z]\d)$)||(^[0-9])/"  required>
like image 314
Ashu Avatar asked Dec 04 '22 03:12

Ashu


2 Answers

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:

Controller:

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

HTML:

<input type="text" class="form-control errorfields" id="postalCode"
 name="postalCode" ng-model="postalCode" 
 ng-pattern="postalCodeValidation "  required>
like image 50
Brian Gerhards Avatar answered Jan 23 '23 01:01

Brian Gerhards


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.

like image 33
richbai90 Avatar answered Jan 23 '23 03:01

richbai90