Angularjs initial form validation with directives

前端 未结 3 2244
春和景丽
春和景丽 2021-02-14 09:49

I have a validation directive called valid-number that is used to set the validity of a form using $setValidity - this works fine for any text values that I type in

3条回答
  •  太阳男子
    2021-02-14 10:10

    $parsers array contains a list of functions that will be applied to the value that model receives from the view (what user types in), and $formatters array contains the list of functions that are being applied to the model value before it's displayed in the view.

    In your directive you correctly used the $parsers array, but you also need to add the $formatters array if you want the initial value to be validated:

    angular.module('test',[]).directive('validNumber',function(){
      return{
        require: "ngModel",
        link: function(scope, elm, attrs, ctrl){
          var regex = /^\d$/;
          var validator = function(value){
            ctrl.$setValidity('validNumber', regex.test(value));
            return value;
          };
    
          ctrl.$parsers.unshift(validator);
          ctrl.$formatters.unshift(validator);
        }
      };
    });
    

    Demo plunker

提交回复
热议问题