我使用的是Angular 11的响应式表单,包含以下7个字段。
- 起始日期(必选)
- 结束日期(必选)
至少有一个字段被填满
<- 电话号码/gh><
- 地址/gh>作者 <
- 用户ID/gh>
我的表单应该是有效的只有当start和结束strong>选择日期,并在其他五个字段中至少填充一个字段。如何将这个自定义验证器放在响应式表单中?下面是我的typescript表单组件:
this.myForm = new FormGroup({
startDate: new FormControl('', Validators.required),
endDate: new FormControl('', Validators.required),
phoneNumber: new FormControl(''),
address: new FormControl(''),
author: new FormControl(),
userID: new FormControl(''),
company: new FormControl('')
}, { validators: dateValidator }
);
下面是一个您的自定义验证器的基本示例:
export const atLeastOneValidator = (keys: string[]) => {
return (group: FormGroup) => {
const { controls } = group;
return keys.some(key => controls[key] && !!controls[key].value)
? null
: { atLeastOne: 'error' };
};
};
你可以这样使用它:
this.myForm = new FormGroup(
{
startDate: new FormControl('', Validators.required),
endDate: new FormControl('', Validators.required),
phoneNumber: new FormControl(''),
address: new FormControl(''),
author: new FormControl(),
userID: new FormControl(''),
company: new FormControl('')
},
{ validators: dateValidator, atLeastOneValidator(['phoneNumber', 'address', 'author', 'userID', 'company']) }
);
我使用了下面的代码来解决这个问题。
this.myForm = new FormGroup(
{
startDate: new FormControl('', Validators.required),
endDate: new FormControl('', Validators.required),
phoneNumber: new FormControl(''),
address: new FormControl(''),
author: new FormControl(),
userID: new FormControl(''),
company: new FormControl('')
},
{ validators: [dateValidator, atLeastOneValidator] }
);
验证器函数:
export const atLeastOneValidator :ValidatorFn=(control: AbstractControl): ValidationErrors | null => {
if((control.get('phoneNumber')?.value!='')||(control.get('address')?.value!='')
||(control.get('author')?.value!='')||(control.get('userID')?.value!='')
||(control.get('company')?.value!='')){
return null;
}
else{
return {atLeastone : 'error'};
}
};