Angular 6 Reactive Forms Custom Validator 从默认数据中获取错误
Angular 6 Reactive Forms Custom Validator getting error shown from Default Data
我在 FormGroup 中有一个 FormArray,每个 FormArray 都有多个 FormGroup,并且可以动态添加它们。
我有一个自定义验证器,它检查每个 FormArray 中的所有数据以验证数据的重复。目前,它还在自己验证初始数据,这会引发错误。
有什么方法可以限制在检查初始数据时错误自己抛出吗?
添加新数据并与现有数据具有相同值时,它工作正常。
for (let assign of this.additionalAssign) {
const fg = new FormGroup({
"payRate": new FormControl(assign.jobRate, Validators.required),
"position": new FormControl(assign.position, Validators.required),
"location": new FormControl(assign.location, Validators.required),
"department": new FormControl(assign.department, Validators.required)
});
fg.validator = this.jobDataValidator.bind(this);
this.addPay.push(fg);
}
验证者:
jobDataValidator(control: FormControl): {[s: string]: boolean} {
let value = this.getJobLocDeptValidity(control);
if(value.length > 0){
return {'sameJobData': true};
}
return null;
}
getJobLocDeptValidity(control: FormControl):any[] {
let additionalAssignments = this.additionalAssignmentsForm.value.payArray;
let test = additionalAssignments.filter(item => !!control.value.position && item.position === !control.value.location && item.location === control.value.location);
return test;
}
截图:
Stackblitz Url:https://stackblitz.com/edit/angular-custom-validator-defaultdata
为避免在原始数据上标记错误,您可以添加检查以确保表单控件是 dirty
,这意味着用户已触摸它。
if(value.length > 0 && control.dirty){
return {'sameJobData': true};
}
我在 FormGroup 中有一个 FormArray,每个 FormArray 都有多个 FormGroup,并且可以动态添加它们。
我有一个自定义验证器,它检查每个 FormArray 中的所有数据以验证数据的重复。目前,它还在自己验证初始数据,这会引发错误。
有什么方法可以限制在检查初始数据时错误自己抛出吗?
添加新数据并与现有数据具有相同值时,它工作正常。
for (let assign of this.additionalAssign) {
const fg = new FormGroup({
"payRate": new FormControl(assign.jobRate, Validators.required),
"position": new FormControl(assign.position, Validators.required),
"location": new FormControl(assign.location, Validators.required),
"department": new FormControl(assign.department, Validators.required)
});
fg.validator = this.jobDataValidator.bind(this);
this.addPay.push(fg);
}
验证者:
jobDataValidator(control: FormControl): {[s: string]: boolean} {
let value = this.getJobLocDeptValidity(control);
if(value.length > 0){
return {'sameJobData': true};
}
return null;
}
getJobLocDeptValidity(control: FormControl):any[] {
let additionalAssignments = this.additionalAssignmentsForm.value.payArray;
let test = additionalAssignments.filter(item => !!control.value.position && item.position === !control.value.location && item.location === control.value.location);
return test;
}
截图:
Stackblitz Url:https://stackblitz.com/edit/angular-custom-validator-defaultdata
为避免在原始数据上标记错误,您可以添加检查以确保表单控件是 dirty
,这意味着用户已触摸它。
if(value.length > 0 && control.dirty){
return {'sameJobData': true};
}