問題描述
根據角度表單構建器/組中其他字段的值運行並設置一個字段的驗證錯誤 (Run and set the validation errors on one field based on the value of other field in angular form builder/group)
我希望自定義函數驗證器在 StartDate 和 EndDate 模糊時運行
component.ts
Createform(){
this.studentForm = formBuilder.group({
StartDate: ['', Validators.required, customFunction(), updateOn: "blur" ],
EndDate: ['', null,customFunction(), updateOn: "blur" ],
}
自定義函數
customFunction(){
if (EndDate <= startDate) {
return of({ invalidDate: true });
}
}
return of(null);
};
}
它設置 CreateForm。在 StartDate 上運行時,controls['StartDate'].errors?.invalidDate 為 true。即使我在 StartDate 上運行該函數,是否可以在 EndDate 上設置此 invalidDate?
自定義函數運行正確,但是當它在 StartDate 上運行時,它會在開始日期設置錯誤數組,但我希望錯誤設置在 EndDate,可以嗎?
參考解法
方法 1:
In your custom function, you can use setErrors function to set error on different field
Custom Function
customFunction(){
if (EndDate <= startDate) {
this.studentForm.form.controls['endDate'].setErrors({'invalidDate': true});;
}
}
return of(null);
};
}
(by Learn AspNet、Nirjhar Vermani)