Where can I get the the error object keys list of the built-in Validators?
For example, if a field uses the required
built-in validator, then I can check:
form.get('myField').hasError('required')
but not all the error object keys have the same name as the validator.
For example, if I use the maxLength
validator, then the following will not work:
form.get('myField').hasError('maxLength')
It is possible to check those values looking directly at the source code:
https://github.com/angular/angular/blob/master/packages/forms/src/validators.ts
In my specific case, the object key error for the maxLength
validator is maxlength
(with lower case L).
I figured it out by looking its implementation in the source code, currently:
static maxLength(maxLength: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const length: number = control.value ? control.value.length : 0;
return length > maxLength ?
{'maxlength': {'requiredLength': maxLength, 'actualLength': length}} :
null;
};
}
so I'm using:
form.get('myField').hasError('maxlength')