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>
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With