Angular 组验证程序不';不影响表单。是否有效
在我看来,当我在angular 5中创建表单组时,如下所示:Angular 组验证程序不';不影响表单。是否有效,angular,forms,validation,Angular,Forms,Validation,在我看来,当我在angular 5中创建表单组时,如下所示: this.myForm = formBuilder.group({ control1: [null, [Validators.required, Validators.minLength(3)]], control2: [null, [Validators.required, Validators.minLength(3)]] }, { validator: comparisonV
this.myForm = formBuilder.group({
control1: [null, [Validators.required, Validators.minLength(3)]],
control2: [null, [Validators.required, Validators.minLength(3)]]
},
{
validator: comparisonValidator(
'control1'
'control2',
this.formGroup)
});
我设置的组验证器(在本例中称为compareControls)在您选中form.isValid
(似乎只考虑单个控件验证器)时不适用于表单
关于如何使组验证程序(comparisonValidator)影响表单有效性的任何想法。例如表单整体有效性
export function comparisonValidator(control1: string, control2: string, group: FormGroup): ValidatorFn {
return (c: AbstractControl): ValidationErrors | null => {
if (group && group.controls) {
const f1 = <AbstractControl>group.get(control1);
const f2 = <AbstractControl>group.get(control2);
if (f1.value >= f2.value) {
return {'case': 'From should be less than To'};
}
}
return null;
};
}
导出函数comparisonValidator(control1:string,control2:string,group:FormGroup):Validator fn{
返回(c:AbstractControl):ValidationErrors | null=>{
if(组和组控件){
const f1=group.get(control1);
const f2=group.get(control2);
如果(f1.value>=f2.value){
返回{'case':'From应该小于To'};
}
}
返回null;
};
}
如果您希望formGroup有效(我建议使用@LuaXD的答案)
如果希望通过formControl生效,可以从中获取其他formControl
导出函数comparisonValidator(control1:string,control2:string):验证器fn{
返回(c:AbstractControl):ValidationErrors | null=>{
const group=c.parent;
if(组和组控件){
const f1=group.get(control1);
const f2=group.get(control2);
如果(f1.value>=f2.value){
返回{'case':'From应该小于To'};
}
}
返回null;
};
}
const myComparisonValidator=comparisonValidator('control1'
“控制2”);
this.myForm=formBuilder.group({
控件1:[null[
需要验证器,
验证器。最小长度(3),
myComparisonValidator
]
],
控制2:[
空[
需要验证器,
验证器。最小长度(3),
myComparisonValidator
]
]
});代码>