angular 反应形式中的自定义验证器永远不会触发
Custom validator in angular reactive forms is never firing
我为简单的表单控件创建了一个非常简单的自定义验证器,例如MatInput,它总是 return 非空,例如无效的。我还添加了一个预构建的验证器,例如必需的。当我启动我的应用程序时,我可以看到 status = INVALID
和 errors.required = true
.
开始输入后,我预计状态将保持 INVALID
和 errors.myError = true
,但这并没有发生。我究竟做错了什么?我在 StackBlitz 上构建了示例。我还在下面
我的 TS & HTML 文件中添加了内容
TS
import { Component } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors, ValidatorFn, Validators} from '@angular/forms';
export function myValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
return { "myError": true };
};
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = new FormControl('', [Validators.required, myValidator]);
}
HTML
<label>
Name:
<input type="text" [formControl]="name">
</label>
{{ name | json }}
我对 Angular 很陌生,我不知道如何调试它。接下来我可以尝试什么?
长话短说:
export class AppComponent {
name = new FormControl('', [Validators.required, myValidator()]);
}
解释:
myValidator
没有被调用,所以你没有得到 ValidatorFn
我为简单的表单控件创建了一个非常简单的自定义验证器,例如MatInput,它总是 return 非空,例如无效的。我还添加了一个预构建的验证器,例如必需的。当我启动我的应用程序时,我可以看到 status = INVALID
和 errors.required = true
.
开始输入后,我预计状态将保持 INVALID
和 errors.myError = true
,但这并没有发生。我究竟做错了什么?我在 StackBlitz 上构建了示例。我还在下面
TS
import { Component } from '@angular/core';
import { AbstractControl, FormControl, ValidationErrors, ValidatorFn, Validators} from '@angular/forms';
export function myValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
return { "myError": true };
};
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = new FormControl('', [Validators.required, myValidator]);
}
HTML
<label>
Name:
<input type="text" [formControl]="name">
</label>
{{ name | json }}
我对 Angular 很陌生,我不知道如何调试它。接下来我可以尝试什么?
长话短说:
export class AppComponent {
name = new FormControl('', [Validators.required, myValidator()]);
}
解释:
myValidator
没有被调用,所以你没有得到 ValidatorFn