javascript - FormControl 验证器始终无效
问题描述
在我之前的问题之后,我正在尝试创建一个自定义验证器,允许用户在文本输入中仅键入特定值。
app.component.ts:
export class AppComponent implements OnInit {
myForm: FormGroup;
allowedValuesArray = ['Foo', 'Boo'];
ngOnInit() {
this.myForm = new FormGroup({
'foo': new FormControl(null, [this.allowedValues.bind(this)])
});
}
allowedValues(control: FormControl): {[s: string]: boolean} {
if (this.allowedValuesArray.indexOf(control.value)) {
return {'notValidFoo': true};
}
return {'notValidFoo': false};
}
}
app.component.html:
<form [formGroup]="myForm">
Foo: <input type="text" formControlName="foo">
<span *ngIf="!myForm.get('foo').valid">Not valid foo</span>
</form>
问题是foo
FormControl 总是假的(myForm.get('foo').valid
总是假的)。
我的实施有什么问题?
解决方案
您只需要在验证正常时返回 null 。并像下面一样更改该方法
private allowedValues: ValidatorFn (control: FormControl) => {
if (this.allowedValuesArray.indexOf(control.value) !== -1) {
return {'notValidFoo': true};
}
return null;
}
推荐阅读
- angular8 - 如何在 dist/ 生成的 index.html 中注入脚本以索引 html 文件
? - android - Integrate Android Studio Project with Azure Pipelines CI/CD
- c# - 如何在 teechart 的任何事件上获取自定义轴
- c# - change mouse button function
- apache - Jmeter 和 Jenkins 集成以生成 Perfmon 图
- c# - 如何在 Blazor 的 DevExpress 数据网格中加载 null 或空集合?
- r - 在 R Markdown 中将一个长方程分成两行
- regex - PL/SQL 正则表达式匹配逗号不在引号内
- c# - 在 1 中组合 2 个或多个正则表达式
- google-maps - 无法获取 Google 地方信息大气数据