在 AngularJS 中,当同一表单中的另一个值发生更改时,如何强制重新验证表单中的字段? [英] In AngularJS, how to force the re-validation of a field in a form when another value in the same form is changed?

查看:19
本文介绍了在 AngularJS 中,当同一表单中的另一个值发生更改时,如何强制重新验证表单中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字段很少的表单,但是选择和输入字段是耦合的:输入的验证取决于用户在选择字段中选择的值.

I have a form with few fields, however a select and an input field are coupled: the validation on the input depends on which value the user chooses in the select field.

我会试着用一个例子来澄清.假设选择包含行星的名称:

I'll try to clarify with an example. Let's say that the select contains names of planets:

<select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.val as c.label for c in planets"></select>

在输入中,我通过名为input-validation"的自定义指令应用自定义验证:

in the input I apply custom validation via a custom directive named "input-validation":

<input id="city" input-validation iv-allow-if="planet==='earth'" class="form-control" name="city" ng-model="city" required>

这里是指令:

.directive('inputValidation', [function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    scope: {
      ivAllowIf: '='
    },
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {

        //input is allowed if the attribute is not present or the expression evaluates to true
        var inputAllowed = attrs.ivAllowIf === undefined || scope.$parent.$eval(attrs.ivAllowIf);

        if (inputAllowed) {
          ctrl.$setValidity('iv', true);
          return viewValue;
        } else {
          ctrl.$setValidity('iv', false);
          return undefined;
        }

      });
    }
  };
}]) 

完整示例可以在 Plnkr 中查看:http://plnkr.co/edit/t2xMPy1ehVFA5KNEDfrf?p=预览

The full example can be examined in Plnkr: http://plnkr.co/edit/t2xMPy1ehVFA5KNEDfrf?p=preview

每当修改选择时,我都需要再次验证输入.这在我的代码中没有发生.我做错了什么?

Whenever the select is modified, I need the input to be verified again. This is not happening in my code. What am I doing wrong?

推荐答案

我已经做了同样的事情来验证开始日期更改结束日期.在 start-date 指令中添加 watch for change of end-date 然后调用 ngModel.$validate() 如果定义了 end-date 新值.

I have done the same thing for validation of start-date on change of end-date. In the directive of start-date add watch for change of end-date and then call ngModel.$validate() in case end-date new value is defined.

    scope.$watch(function () {
        return $parse(attrs.endDate)(scope);
    }, function () {
        ngModel.$validate();
    });

要采取的重要部分是在指令内调用 ngModel.$validate().

The important part to take is call to ngModel.$validate() inside the directive.

注意您应该使用 $validators 进行上面的自定义验证才能工作.阅读此处,$parsers是旧方法 - 从 angularjs 1.3 开始使用 $validators

Note you should use $validators for custom validations above to work. read here, $parsers is the old way - from angularjs 1.3 use $validators

固定 PLUNKER 链接

这篇关于在 AngularJS 中,当同一表单中的另一个值发生更改时,如何强制重新验证表单中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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