自定义表单验证指令比较两个字段 [英] Custom form validation directive to compare two fields

查看:110
本文介绍了自定义表单验证指令比较两个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手的角度,和我绊倒的东西表单验证指令如何角的工作。

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 individual fields, but I'm trying to add a validation which will compare two form fields (both of which are elements of a model).

下面是一个形式框架:

<form name="edit_form" >
  <input name="min" type="number" ng-model="field.min"/>
  <input name="max" type="number" ng-model="field.max"/>
</form>

<div class="error" ng-show="edit_form.min.$dirty || edit_form.max.$dirty">
  <small class="error" ng-show="(what goes here?)">
    Min cannot exceed max
  </small>
</div>

总之,我想写一个指令,并用它来显示/隐藏这个 small.error 如果最大都有价值,但分钟&GT;最大。我如何可以访问一个指令里面的这两个领域?是指导这个工作的工具?

In short, I want to write a directive and use it to show/hide this small.error if min and max both have values but min > max. How can I access both fields inside one directive? Is a directive the right tool for this job?

推荐答案

许多方法来皮肤猫。

<大骨节病> 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
    };

  }
]);

用法:

<input name="min" type="number" ng-model="field.min" lower-than="{{field.max}}" />
<span class="error" ng-show="form.min.$error.lowerThan">
  Min cannot exceed max.
</span>

这篇关于自定义表单验证指令比较两个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆