Thursday, 28 July 2016

Angular JS : Create directive to validate the phone numbers.

Step 1: Add "phoneValidate" directive into your directive js file. In my case I have created "myDirective" for create custom directives.


var directive = angular.module("myDirective", []);

directive.directive('phoneValidate', [function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            elem.on('keyup', function () {
                scope.$apply(function () {
                    var regex = /^\s*[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;
                    var v = regex.test(elem.val());
                    ctrl.$setValidity('pwmatch', v);
                });
            });
        }
    }
}]);


Step 2: For consume this directive you just need to add attribute named "phone-Validate" to Phone number text box.

<form class="form-horizontal" name="myForm" novalidate>
       <div class="form-group" ng-class="{'has-error'myForm.inputPhoneNumber.$invalid &&
                                     myForm.inputPhoneNumber.$dirty}">
          <label>Phone number</label>
          <input  id="inputPhoneNumber"
                       name="inputPhoneNumber"
                       type="text" phone-Validate
                       ng-model="phoneNumber" placeholder="phone" />
     </div>
</form>


Following regex you can use for validate the phone numbers:


Regex to validate International phone numbers:

/^\s*(?:\+?(\d{1,3}))??[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;

Example:
1234567890
+11234567890
+1(123) 456-7890
(123) 456-7890
123-456-7890
+1123-456-7890
123.456.7890
+1123.456.7890
(734) 555.1212
+1(734) 555.1212


Regex to validate only 10 digits:
/^\s*[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/

Example:
1234567890

No comments:

Post a Comment