Angularjs initial form validation with directives

前端 未结 3 2184
春和景丽
春和景丽 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条回答
  •  Happy的楠姐
    2021-02-14 10:14

    After (>=) angular 1.3.1 version was released you could implement that behaviour with a little bit correct way, following angular validation directives style (e.g. required, maxlength).

    In that case you have to append your validator as property of $validators array and there are no need in $parsers or $formatters anymore:

    var app = angular.module('test', []);
    
    app
      .directive('validNumber', function() {
        return {
          require: "ngModel",
          link: function(scope, elm, attrs, ctrl) {
            var regex = /^\d+$/;
    
            ctrl.$validators['validNumber'] = function(modelValue, viewValue) {
              return regex.test(viewValue);
            };
          }
        };
      });
    
    app.controller('NumberCtrl', NumberCtrl);
    
    function NumberCtrl($scope) {
      $scope.amount = '5z';
    };
    input.ng-invalid {
      background-color: #FA787E;
    }
    
    
    
    Doesn't look like an integer

提交回复
热议问题