My validation process involves both frontend and backend components. While the frontend validation is functioning properly, I am encountering difficulties with integrating backend validation results into the frontend (manually marking controls as invalid based on backend validation).
The issue lies in populating form controls with errors - it seems that simply using
this.formBuiltWithFormBuilder.setErrors()
and passing an object with errors does not automatically populate all controls within the form. The entire form only becomes invalid when all field statuses remain unchanged.
Currently, my approach involves:
// Example of incoming formErrors:
// (it can also be nested for nested forms)
// {
// phone: {
// phoneNumberNoMatch: "The input does not match..."
// }
// }
@Input() public formErrors: ValidationErrors;
public detailsForm: FormGroup;
public ngOnInit() {
this.createForm();
}
public ngOnChanges() {
this.updateFormErrors(this.formErrors);
}
private createForm(account: AccountInterface) {
this.detailsForm = this.fb.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required]
});
}
private updateFormErrors(errors: any) {
if (this.detailsForm) {
// Trying to populate included form controls with errors
this.detailsForm.setErrors(errors);
}
}
I have considered manually iterating through the errors object and applying errors for each control individually, but I believe this solution may not be ideal especially for nested forms.
Is there a way to automatically populate form controls with errors?