Tuesday, January 2, 2018

How to use ng-pattern to validate the phone format in AngularJS Web application.

we can directly apply the regular expression pattern to the ng-pattern directive to validate the phone number format. however this approach will limit to mandatory field only. you will see the annoying message if you use this implementation.

<input type="text" ng-model="phoneNumber" id="input" name="phoneNumber" 
 ng-pattern="/^\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})$/" /><br>

we can use different approach to handle this validation, we will use ng-required to validate the required validation, then we will implment a function to take care of phone format validation.



<input type="text" name="phoneNumber" ng-model="phoneNumber" ng-required="requiredCondition" ng-pattern="phoneNumberPattern" />

in the controller javascript file we will implement a validatePhoneNumber function, which will only trigger when the phone field is not blank.

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






 
 





No comments:

Post a Comment