mat*_*olo 5 angular-validation angular
我正在使用 angular 7 并且我有一个包含两个输入字段的表单,而第一个总是需要的,只有在选中复选框时才需要第二个。
我正在尝试将 FormGroup 与自定义验证器一起使用:
<form [formGroup]="exampleForm">
<mat-form-field>
<input matInput placeholder="first" formControlName="first">
</mat-form-field>
<mat-checkbox [(ngModel)]=" checked" [ngModelOptions]="{standalone:true}">Make second input field required</mat-checkbox>
<mat-form-field>
<input matInput placeholder="second" formControlName="second">
</mat-form-field>
</form>Run Code Online (Sandbox Code Playgroud)
exampleForm: FormGroup;
checked: boolean;
ngOnInit() {
this.exampleForm = new FormGroup({
'second': new FormControl('', [this.validateIfChecked()]),
'first': new FormControl('example', [Validators.required])
});
}
validateIfChecked(): ValidatorFn {
return (control: AbstractControl): {
[key: string]: any
} | null => {
if (this.checked) {
return control.value ? null : {
'err': true
};
}
return null;
}
}Run Code Online (Sandbox Code Playgroud)
问题是只有当两个输入字段中的文本更新时才执行验证,而如果我选中/取消选中复选框,状态不会改变,并且强制验证我必须更改第二个文本框中的文本。
在这里你可以看到一个关于 stackblitz 的例子:如果你选中复选框,状态不会改变。
当复选框状态更改时,如何强制验证?
您需要使用跨域验证。将复选框包含在表单组中
<form [formGroup]="exampleForm">
<mat-form-field>
<input matInput placeholder="first" formControlName="first">
</mat-form-field>
<mat-checkbox formControlName="checked">Make second input field required</mat-checkbox>
<mat-form-field>
<input matInput placeholder="second" formControlName="second">
</mat-form-field>
</form>
Run Code Online (Sandbox Code Playgroud)
ngOnInit() {
this.exampleForm = new FormGroup({
'second': new FormControl(''),
'checked': new FormControl(false),
'first': new FormControl('example')
}, [this.validateIfChecked()]);
}
validateIfChecked(): ValidatorFn {
return (form: FormGroup): ValidationErrors | null => {
const checked = form.get('checked');
const second= form.get('second');
if (checked && !second) {
return {
'err': true
};
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果“checked”为 true,则需要“second”
如果有疑问https://angular.io/guide/form-validation#cross-field-validation
| 归档时间: |
|
| 查看次数: |
16594 次 |
| 最近记录: |