I am facing the problem as described in this topic
I am trying to add a validator to a form group in which I have already 3 validators on form controls. So I have a form group with 6 controls, 3 of them have a required validator. And I want to validate globally my form to check if a date period is correctly described, so I add a validator to my form group.
Here is an example of code :
this.identifierForm = this.formBuilder.group({
id: [],
type: [null, Validators.required],
value: [null, Validators.required],
validFrom: [],
validUntil: [],
authority: [null, Validators.required],
});
this.identifierForm.setValidators(
FormValidator.dateOrderValidator(
this.identifierForm,
'validFrom',
'validUntil',
this.i18nService
)
);
This results in only the form group validator to work. The form control validators are just ommited. If I delete my form group validator, everything is working well in my form controls validators.
How can I do to "add" validator to my form group without overriding the included form controls validators?
I saw that angular 12 added the "addValidators" method to the FormGroup but I am not able to use this version at the moment.
EDIT: I just tryed to define my formgroup validator at instantiation timebut result is still the same
this.identifierForm = this.formBuilder.group(
{
id: [],
type: [null, Validators.required],
value: [null, Validators.required],
validFrom: [],
validUntil: [],
authority: [null, Validators.required],
},
{
validators: [
FormValidator.dateOrderValidator('validFrom', 'validUntil', this.i18nService),
],
}
);
Here is my validator :
dateOrderValidator(
startDateFieldName: string,
endDateFieldName: string,
i18nService: DngI18nService
): ValidatorFn {
return (formGroup: FormGroup): ValidationErrors | null => {
resetErrors(formGroup);
const startDate = formGroup.controls[startDateFieldName]?.value;
const endDate = formGroup.controls[endDateFieldName]?.value;
if (Date.parse(startDate) >= Date.parse(endDate)) {
formGroup.controls[startDateFieldName].setErrors({
error: i18nService.instant('invalidDatePeriod') as string,
});
formGroup.controls[endDateFieldName].setErrors({
error: i18nService.instant('invalidDatePeriod') as string,
});
return { error: i18nService.instant('invalidForm') as string };
}
return null;
};
},