Custom form validation directive to compare two fields

后端 未结 6 803
借酒劲吻你
借酒劲吻你 2020-11-28 08:54

I\'m an angular newbie, and I\'m stumbling over something in how angular\'s form validation directives work.

I know that I can fairly easily add directives to in

6条回答
  •  萌比男神i
    2020-11-28 09:38

    Many ways to skin a cat.

    PLUNKER

    app.directive('lowerThan', [
      function() {
    
        var link = function($scope, $element, $attrs, ctrl) {
    
          var validate = function(viewValue) {
            var comparisonModel = $attrs.lowerThan;
    
            if(!viewValue || !comparisonModel){
              // It's valid because we have nothing to compare against
              ctrl.$setValidity('lowerThan', true);
            }
    
            // It's valid if model is lower than the model we're comparing against
            ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) < parseInt(comparisonModel, 10) );
            return viewValue;
          };
    
          ctrl.$parsers.unshift(validate);
          ctrl.$formatters.push(validate);
    
          $attrs.$observe('lowerThan', function(comparisonModel){
            // Whenever the comparison model changes we'll re-validate
            return validate(ctrl.$viewValue);
          });
    
        };
    
        return {
          require: 'ngModel',
          link: link
        };
    
      }
    ]);
    

    Usage:

    
    
      Min cannot exceed max.
    
    

提交回复
热议问题