繁体   English   中英

Angular 响应式表单自定义验证未在触摸时触发

[英]Angular Reactive form custom validation is not triggering on touch

我有一个 angular 反应形式,默认Validation.required和一个CustomValidation CustomValidation中,我打算检查控件是否被触摸,但不知何故这不起作用。

 import { CustomValidation } from './CustomValidator'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { customForm: FormGroup; constructor(private fb: FormBuilder) {} ngOnInit() { this.customForm = this.fb.group({ customInput: [ '', [Validators.required, CustomValidation.customEmailValidation()], ], }); } } // CustomValidation.ts import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export class CustomValidation { static customEmailValidation(): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { if (control.touched && control.value.length === 0) { console.log(control); return { customError: { hasError: true, errorType: 'empty field', // this can be any name errorLabel: 'test', }, }; } return null; }; } }
 <form [formGroup]="customForm"> <input formControlName="customInput" /> <button [disabled]="this.customForm.invalid">Submit</button> </form>

我期望 static 方法customEmailValidation中的 console.log 将在触摸该字段时记录控件 object。 通过触摸我的意思是,我只点击输入。但那没有发生。

我也试过使用updateOn

customInput: ['', {validators:[CustomValidation.customEmailValidation(),Validators.required],updateOn:"blur"}]

请帮助我理解为什么它不起作用。

Stackblitz 演示

首先,在你触摸它之前,form.touched 是假的。 这就是第一个值。

该值首次作为 form.touched

所以你会得到 touched property 为假。

如果你打算让它被触摸,只需 go 和this.form.markAsTouched()然后执行逻辑。

您描述的是focusin事件,而不是touched state。

来自 Angular 文档:

touched: boolean Read-Only 如果控件标记为已触摸,则为真。

一旦用户在控件上触发了模糊事件,控件就会被标记为已触摸。

你在期待这个:

通过触摸我的意思是,我只点击输入。但那没有发生。

此外,自定义验证器应该与表单输入 state 无关。您可以通过绑定到focusin事件并使用它来翻转touched的 state 来实现您想要的。我不明白您为什么要从 UX 执行此操作透视,但是嘿。

模板

<form [formGroup]="customForm">
  <input (focusin)="onFocusIn($event)" formControlName="customInput" />
  <button [disabled]="this.customForm.invalid">Submit</button>
</form>
<span *ngIf="this.customForm.invalid && this.customForm.touched"
  >VERY SERIOUS ERROR</span
>

成分

  onFocusIn(event) {
    this.customForm.markAsTouched();
    console.log('focus');
  }

验证器

  static customEmailValidation(): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      if (control.value.length === 0) {
        console.log(control);
        return {
          // ...control.errors,
          customError: {
            hasError: true,
            errorType: 'empty field', // this can be any name
            errorLabel: 'test',
          },
        };
      }
      return null;
    };
  }

堆栈闪电战在这里。

您可以在此处从 Angular 文档中阅读有关自定义表单控件的更多信息。

暂无
暂无

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

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