angular - Angular Ionic - 仅当某个字段是某个值时才验证表单
问题描述
我很确定这很容易做到,但我无法在任何地方找到解决方案。
我有一个formGroup
被调用的议程。在启用提交之前,所有字段都是必填且有效的。我还希望最后一个字段仅在它等于用户输入的某个数字(由 定义solution
)时才有效。我简化了下面的代码:
<form (ngSubmit)="submitForm()" [formGroup]="agenda" class="bodytext">
<ion-input type="text" name="email" formControlName="email" required></ion-input>
<ion-input type="text" name="userSolution" formControlName="userSolution" required></ion-input>
<ion-button type="submit" expand="block" [disabled]="agenda.invalid">Submit</ion-button>
</form>
然后在 ts 文件中有我的构造函数:
constructor( http: HttpClient, private formBuilder: FormBuilder) {
this.http = http;
this.agenda = this.formBuilder.group({
email: [''],
userSolution: [''],
});
}
解决方案
我在 stackblitz 上创建了一个工作示例,当条件为真时,我假设数字为 20。您还可以在初始化表单时使用所需的验证器。
我使用了一个自定义验证器,它返回错误名称作为键,{errorName: true}
如果条件不匹配,则返回布尔值 true 作为值,并且该错误名称可用于验证错误消息。
export class AppComponent implements OnInit {
agenda: FormGroup;
solution = 20;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.initForm();
}
initForm() {
this.agenda = this.formBuilder.group({
email: ["", Validators.required],
userSolution: ["", [Validators.required, this.myValidator(this.solution)]]
});
}
myValidator(num: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if (
control.value !== undefined &&
(isNaN(control.value) || control.value != num)
) {
return { notEqual: true };
}
return null;
};
}
}
形式-
<form [formGroup]="agenda" class="bodytext">
<input type="text" name="email" formControlName="email">
<input type="text" name="userSolution" formControlName="userSolution">
<button type="submit" expand="block" [disabled]="agenda.invalid">Submit</button>
</form>
演示链接 - stackBlitz
推荐阅读
- performance - Jmeter中的带宽控制测试
- javascript - 尝试映射数组时出错....无法读取未定义的属性“映射”
- hibernate - Spring Boot:如何在自定义验证中为嵌套对象的字段添加自定义名称
- sql - 查找表记录中的缺失间隙
- python - 在 seaborn 中使用 FacetGrid 缩放构面以适应数据并使用最大可用空间
- laravel - 重试 MaxAttemptsExceededException 作业
- node.js - 使用 session 和 node.js 检查用户是否登录
- angular - 使用 Angular 4 的 Github 应用程序
- android - 带有适配器的自动完成文本视图显示奇怪的问题
- delphi - onResize 和 onResized 有什么区别?