0

i have this directive

angular.module('tutors.components')
  .directive('formValidator', function() {
    return {
      restrict: 'A'      
      link: function (scope, element, attrs) {
        function nameValidator (input) {
          var regExp : "/^[a-zA-Z']*$/";
          var validator : regExp.test(input);
          return validator;
        }  
      };
    });

And this html

    <input form-Validator
           type="text"
           required
           name="firstName"
           class="form-control"
           ng-maxlength="20"
           placeholder="First name"
           ng-model="user.firstName"
           ng-disabled="vm.isLoading"
           tooltip="{{requiredMsg}}"
           tooltip-placement="top"
           tooltip-trigger="focus"
           tooltip-enable="signupForm.firstName.$error.required && signupForm.firstName.$touched">

and i want to run the directive so it validates the text entered in the input, i have tried using an ng-pattern like this ng-pattern="/[a-zA-Z]+/" but that didn't work (i still prefer using it over the directive)

  • 1
    Maybe I'm missing something but you define nameValidator in your link function but never call it on anything. – lintmouse Dec 03 '15 at 19:34

1 Answers1

0

Your directive should be be having small case form-validator to get call to the directive by compiler.

Additionally you need to change your nameValidator function code to below.

.directive('formValidator', function() {
  return {
    restrict: 'A',
    require: 'ngModel', //to get ngModelController
    link: function(scope, element, attrs, ngModel) {
      function nameValidator(input) {
          var regExp = "/^[a-zA-Z]$/";
          var validator = regExp.test(input);
          return validator;
      }
      ngModel.$validators.push(nameValidator); //should pushed to validators to validate
    }
  }
})

OR ng-pattern should be fine, only it should have ^(start) & $(end)

ng-pattern="/^[a-zA-Z]*$/"

Demo Plunkr

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299