I have a reactive form using angular 7 and each field has more than one pattern to validate. I want to make an error message for each pattern but I can't find a way to identify them.
In my Ts file I have something like this:
myfield: ['', [
//Validators.pattern(/^/),
Validators.pattern(/^/),
Validators.pattern(/^/)]],
And in my html file;
<p class="error" *ngIf="myFormGroup.get('myField').hasError('pattern')">
pattern error</p>
I want to be able to separate each one of my patterns to show the appropiate error message Something like:
<p class="error" *ngIf="myFormGroup.get('myField').hasError('pattern1')">
pattern error 1</p>
<p class="error" *ngIf="myFormGroup.get('myField').hasError('pattern2')">
pattern error 2</p>
Any thoughts about this? My form has many fields, validators and components. So I am looking for a simple way.
You need custom validators (https://angular.io/guide/form-validation#custom-validators):
export function customValidator(): ValidatorFn {
return (control: AbstractControl): { [key: string]: {message: string} } | null => {
if (!new Regexp(/regexpPattern1Here/).test(control.value)) {
return {
pattern1Error: {
message: `Error message for pattern 1`
}
};
}
if (!new Regexp(/regexpPattern2Here/).test(control.value)) {
return {
pattern2Error: {
message: `Error message for pattern 2`
}
};
}
return null;
};
}
And instead of doing
myfield: ['', [
//Validators.pattern(/^/),
Validators.pattern(/^/),
Validators.pattern(/^/)]],
, do
myfield: ['', [customValidator()]],
the pattern validator returns the violated pattern in it's ValidationErrors object. so you could possibly leverage that like this:
<p class="error" *ngIf="myFormGroup.get('myField').errors?.pattern">
<ng-container *ngIf="myFormGroup.get('myField').errors.pattern.requiredPattern === pattern1">Pattern 1 Error</ng-container>
<ng-container *ngIf="myFormGroup.get('myField').errors.pattern.requiredPattern === pattern2">Pattern 2 Error</ng-container>
</p>
and so on. A limitation here is that it will only return one violated pattern at a time due to the nature of the errors object being a keyed object that can only have one pattern violation at a time. If you need to display multiple pattern errors at once, then you will need a custom validator that supports multiple patterns.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With