When validating a form for a call center, the fields are usually required to be filled in a specific order. If a user tries to skip ahead, I want to raise an error for multiple fields. I have discovered a method that seems to work as shown below:
export const recordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
if(!firstField.value && !secondField.Value && !thirdField.value)
{
firstField.setErrors({ "firstFieldError" : true});
secondField.setErrors({ "secondFieldError" : true});
return {"firstFieldError" : true, "secondFieldError" : true};
}
}
Both firstField and secondField display errors correctly.
After reading the documentation, I realized that ValidationErrors is simply a map of errors without any methods. I tried casting an existing map to ValidationErrors like this:
export const recordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
if(!firstField.value && !secondField.Value && !thirdField.value)
{
firstField.setErrors({ "firstFieldError" : true});
secondField.setErrors({ "secondFieldError" : true});
let errorMap = new Map();
errorMap.set("firstFieldError",true);
errorMap.set("secondFieldError",true);
let errorValidators:ValidationErrors = errorMap;
return errorValidators;
}
}
However, this method does not raise any errors.
The template structure I am using is:
<mat-form-field>
<input formControlName="firstField" type="datetime-local" placeholder="First Field" [errorStateMatcher]="errorMatcher" matInput>
<mat-error *ngIf="Form.errors?.firstFieldError">
First field error!
</mat-error>
</mat-form-field>
I need help in understanding why the first method works and the second does not.