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

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

问题描述

我是一个 angular 新手,我在 angular 的表单验证指令的工作方式方面遇到了一些问题.

我知道我可以很容易地向单个字段添加指令,但我正在尝试添加一个验证来比较两个表单字段(两者都是模型的元素).

这是一个表单骨架:

简而言之,如果 minmax 都有值但 min >最大.如何访问一个指令中的两个字段?指令是适合这项工作的工具吗?

解决方案

给猫剥皮的多种方法.

PLUNKER

app.directive('lowerThan', [功能() {var link = function($scope, $element, $attrs, ctrl) {var 验证 = 函数(视图值){var compareModel = $attrs.lowerThan;if(!viewValue || !comparisonModel){//这是有效的,因为我们没有什么可比较的ctrl.$setValidity('lowerThan', true);}//如果模型低于我们比较的模型,则有效ctrl.$setValidity('lowerThan', parseInt(viewValue, 10) 

用法:

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).

Here's a form skeleton:

<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>

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?

解决方案

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:

<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天全站免登陆