Angular2 - 模糊时的 FormControl 验证

标签 angular typescript validation angular-validation

我正在考虑添加一些基本的电子邮件验证,以检查用户是否输入了正确的电子邮件地址。目前使用下面的方法,验证会随着用户键入而更新,当输入一个字符后出错时,这看起来很奇怪。

validEmail(c: Control){
if(!c.value.match('[a-z0-9!#$%&\'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&\'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?')){
  return {
    validEmail: true
  };
}
return null;
}    

ctrlEmailAddress: Control = new Control('', Validators.compose([
Validators.required, this.validEmail]));

我想知道是否有可能在字段模糊时触发验证,就像在 angularJS 中一样:

ng-model-options="{ updateOn: 'blur' }"

我知道 html 中输入字段上的模糊选项,但这不会使我的控件出错,除非有办法将控件置于错误状态。

谁能帮我指明正确的方向?

谢谢。

编辑:我正在寻找 angular2 解决方案,而不是 angularJS 解决方案。

最佳答案

编辑 2

作为Alexofficial documentation说,Angular 版本 5.0.0 为您的 ngModel updateOn: 'blur'

提供了新选项
this.email = new FormControl(null, {
   validators: Validators.required,
   updateOn: 'blur'
});

您还可以使用其他更新选项:change(默认)、blursubmit


原创

我使用指令删除焦点上的整个验证并在模糊事件后将其返回。它基于 Cristian Deschamps 的回答。

我只在模糊时更新有效性,所以如果值在聚焦之前无效,那么聚焦之后也会无效。但如果您开始输入,有效性将被更新。

出于某些原因,清除顺序很有意义,所以我首先清除异步验证器。

任何提供的建议都会有所帮助 =)

import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[validate-onblur]',
  host: {
    '(focus)': 'onFocus($event)',
    '(blur)': 'onBlur($event)'
  }
})
export class ValidateOnBlurDirective {
    private validators: any;
    private asyncValidators: any;
    constructor(public formControl: NgControl) {
    }
    onFocus($event) {
      this.validators = this.formControl.control.validator;
      this.asyncValidators = this.formControl.control.asyncValidator;
      this.formControl.control.clearAsyncValidators();
      this.formControl.control.clearValidators();
    }

    onBlur($event) {
      this.formControl.control.setAsyncValidators(this.asyncValidators);
      this.formControl.control.setValidators(this.validators);
      this.formControl.control.updateValueAndValidity();
    }
}

另外,敬请关注本Angular 2 github thread关于onBlur验证


编辑 1

还有另一个问题 - 如果我只是单击该字段并在单击后离开 - 将调用验证。如果你有任何关于它的通知(或服务器调用)——它会在你每次这样做时出现。所以你可以添加 wasChanged 属性并像这样使用它:

    @Directive({
        selector: '[validate-onblur]',
        host: {
            '(focus)': 'onFocus($event)',
            '(blur)': 'onBlur($event)',
            '(keyup)': 'onKeyup($event)',
            '(change)': 'onChange($event)',
            '(ngModelChange)': 'onNgModelChange($event)'
        }
    })
    export class ValidationOnBlurDirective {
        private validators: any;
        private asyncValidators: any;
        private wasChanged: any;
        constructor(public formControl: NgControl) {
        }
        onFocus($event) {
            this.wasChanged = false;
            this.validators = this.formControl.control.validator;
            this.asyncValidators = this.formControl.control.asyncValidator;
            this.formControl.control.clearAsyncValidators();
            this.formControl.control.clearValidators();
        }
        onKeyup($event) {
            this.wasChanged = true; // keyboard change
        }
        onChange($event) {
            this.wasChanged = true; // copypaste change
        }
        onNgModelChange($event) {
            this.wasChanged = true; // ng-value change
        }
        onBlur($event) {
            this.formControl.control.setAsyncValidators(this.asyncValidators);
            this.formControl.control.setValidators(this.validators);
            if (this.wasChanged)
                this.formControl.control.updateValueAndValidity();
        }
    }

关于Angular2 - 模糊时的 FormControl 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33866824/

相关文章:

javascript - 如何通知另一个组件该方法执行

c++ - 输入的整数验证

javascript - 带有输入元素的AngularJS自定义指令,从外部传递验证器

javascript - 如何在 Angular 2/4 应用程序的 NgModule 中将对象传递给服务构造函数

angular - 您将如何修复此 "Promise<any>' 提供与签名 '(value: any): {} | PromiseLike<{}>"不匹配的错误

javascript - Angular Google map 组件 TypeError : Cannot read property 'nativeElement' of undefined

typescript - 如何检查表单控件是否以 react 形式被禁用

javascript - 在 Angular 2 中使用普通 js 代码 (angular-cli)

typescript - "FindConfigFiles"任务意外失败。 VS2015 Angular 2 的 Visual Studio 和 Typescript 问题

html - 在用户提交的数据中不转义 & 符号是否存在安全风险?