简体   繁体   English

在模糊/焦点事件上使用$ validators

[英]Use $validators on blur/focus events

Now, in my validation directive I set validation state 'manually', like this: 现在,在我的验证指令中,我设置“手动”验证状态,如下所示:

$element.on('focus', function() {
    $scope.$apply(function() {
       ngModelCtrl.$setValidity('length', true);
    });
 });

 $element.on('blur', function() {
    $scope.$apply(function() {
        if (ngModelCtrl.$modelValue && ngModelCtrl.$modelValue.length === +$attrs.maxlength) {
            ngModelCtrl.$setValidity('length', true);
        }      
        else if (ngModelCtrl.$modelValue.length < +$attrs.maxlength && ngModelCtrl.$modelValue.length > 0) {
            ngModelCtrl.$setValidity('length', false);
        }
     }
 });

But I want to set validation states with $validators with saving validation behaviour (on blur/focus events). 但是我想用$validators设置验证状态并保存验证行为(在模糊/焦点事件上)。

I can't use ng-model-options with updateOn: 'blur' . 我不能将ng-model-optionsupdateOn: 'blur'

Is other options to do this? 还有其他选择吗?

So to use a custom validator you will need to structure your directive a little differently. 因此,要使用自定义验证程序,您将需要对指令的结构进行一些改动。 The major difference is you need to require ngModel . 主要区别在于您需要ngModel

Directive 指示

return {
     require: 'ngModel',
     link: function(scope, element, attrs, ngModel) {
        // Run validator for maxLenth
        ngModel.$validators.customMaxLength = function(value) { 
          var status = false;
            if(value.length <= attrs.maxLengthValidator) {
              console.log(attrs.maxLengthValidator);
            status = true;
          }
              return status;
        };
    }
  }

Something important to note. 重要注意事项。 If you are using an attribute to do your validate against and the value can change you need to watch the value and run your validator function against in manually. 如果使用属性进行验证,并且值可以更改,则需要监视值并手动运行in的验证函数。 Because the model does not change the validator would not fire automatically. 由于模型未更改,因此验证程序不会自动触发。

Add the following to the directive 将以下内容添加到指令中

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

If you validator returns false you form will automatically have $valid set to false 如果您的验证程序返回false,您的表单将自动将$valid设置为false

HTML HTML

In the example below I use angular-messages to display the valid output. 在下面的示例中,我使用角度消息来显示有效输出。 This is an optional module that needs included. 这是一个可选模块,需要包含在内。

<form name="myForm">
    <div class="form-group" ng-class="{'has-error':myForm.testField.$invalid}">
      <label class="control-label" for="testInput">Test Field</label>
      <input class="form-control" type="text" name="testField"  
        max-length-validator="3" required ng-model="testField"/>
    </div>
</form>

    <div ng-messages ng-messages-multiple class="bg-danger" for="myForm.testField.$error">
                <div ng-message when="required">Please enter value</div>
                <div ng-message when="customMaxLength">To Long</div>
    </div>

Custom Validator Example 自定义验证器示例


In regards to your question about firing the validator on blur 关于您关于在模糊时触发验证器的问题

You don't really want to update the ngModel if the model value is invalid. 如果模型值无效,则您实际上并不想更新ngModel。

What I would recommend is using styles and a focus attribute with the field to toggle the display based on the focus of the field. 我建议在字段中使用样式和focus属性,以基于字段的焦点切换显示。

Add something like the following to your input field 在您的输入字段中添加以下内容

ng-focus="myForm.testField.focus=true" ng-blur="myForm.testField.focus=false"

Then use checks with ng-class , ng-show or ng-hide to update your display. 然后使用ng-classng-showng-hide进行检查以更新显示。

This has been added to the plnkr 这已添加到plnkr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM