【问题标题】:AngularJS form validation triggered by other fields其他字段触发的 AngularJS 表单验证
【发布时间】:2016-05-27 22:39:43
【问题描述】:

我有一个 angularjs 应用程序,必须使用自定义业务规则进行表单验证。 问题是我对特定输入字段的验证规则依赖于其他字段,除了实际模型值发生变化时,我不知道如何触发验证。

该案例是员工的动态列表,每个员工都有一个要输入的一天中时间的动态列表。一条规则是这些时间不能重叠,这意味着一个值可能由于另一个值被更改而无效,反之亦然。 我还必须为每个字段显示一条错误消息。

表单内容是从具有几层嵌套转发器的数据模型生成的。 我制作了一个自定义指令,其中包含不同的验证规则,并且当该字段更改时它会很好地触发。 我正在使用 ngMessages 根据违反的业务规则显示适当的错误消息。

问题是,当某个特定字段发生更改时,如何触发对所有其他字段的验证?最好我应该触发对正在更改值的员工的所有字段的验证,因为一个员工的值不会影响其他员工的验证。

这里的小提琴有一个简化版本的我的例子,其中“重叠”规则只是检查两个数字是否相同。

html:

<form name="demoForm">
    <div ng-repeat="employee in list">
    <div ng-bind="employee.name"></div>
    <div ng-repeat="day in employee.days" ng-form="employeeForm">

      <input ng-model="day.hours" name="hours" custom-validate="{day: day, days: employee.days}" ng-model-options="{allowInvalid:true}" />
      <span ng-messages="employeeForm.hours.$error">
        <span ng-message="number">Should be a number.</span>
      <span ng-message="businessHours">The number is outside business hours.</span>
      <span ng-message="max">The number is too large.</span>
      <span ng-message="overlap">The number must be unique for each employee.</span>
      </span>
    </div>
    <br/>
  </div>
</form>

验证指令:

angular.module('app').directive('customValidate', [validator]);

function validator() {
  return {
    restrict: 'A',
    require: 'ngModel',
    scope: {
      data: '=customValidate'
    },
    link: linkFunc,
  };

  function linkFunc(scope, element, attrs, ctrl) {
    ctrl.$validators.number = function(value) {
      return value === "" || Number.isInteger(+value);
    }

    ctrl.$validators.businessHours = function(value) {
      // imagine other validation data here
      return value === "" || (value >= 1 && value <= 10);
    }

    ctrl.$validators.overlap = function(value) {
      if (value === "") {
        return true;
      }

      // find all other entries with identical value excluding self
      var identical = scope.data.days.filter(function(x) {
        return x !== scope.data.day && +x.hours === +value;
      });

      return identical.length === 0;
    };
  }
}

在这里提琴: http://jsfiddle.net/maxrawhawk/dvpjdjbv/

【问题讨论】:

  • 在与 scope.$watch 搏斗之后,我自己找到了解决方案。

标签: angularjs forms validation ng-messages


【解决方案1】:

答案: 指令链接函数末尾的这段小代码:

scope.$watch('data', function(){
        ctrl.$validate();
    }, true);

观察标记给出的与验证相关的数据,其中最重要的细节“真”作为第三个参数,使 $watch 检查对象是否相等。 更新的小提琴: http://jsfiddle.net/maxrawhawk/dvpjdjbv/12/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2017-11-13
    • 2023-03-10
    • 2014-02-22
    相关资源
    最近更新 更多