How to display max length based on FormControl’s validator

Unfortunately `hasValidator` does not work well with validators created dynamically like `Validator.maxLength` but there is a solution that allows getting information about maxLength value anyway.

You can view the source code for this project by following this link: GitHub

Demo

Take a look at the title hint. Try to provide a title longer than 15 chars.

Problem with hasValidator

Let’s create a simple FormControl with maxLength validator. To check if the control has some validator we can use the hasValidator method but it does not work correctly for Validators.maxLength(15) because calling Validators.maxLength(15) creates another reference and the implementation of hasValidator check validators by reference.

1
import { FormControl, Validators } from "@angular/forms";
2
3
const titleControl = new FormControl(null, [Validators.maxLength(15)]);
4
titleControl.hasValidator(Validators.maxLength(15)); // -> false
5
6
// ---
7
8
const max15Chars = Validators.maxLength(15);
9
const titleControl = new FormControl(null, [max15Chars]);
10
titleControl.hasValidator(max15Chars); // -> true

Checking if a control has a maxLength validator without hasValidator

To check if the control has a maxLength validator let’s first take a look into maxLength implementation.

1
// The fragment of maxLength validator
2
export function maxLengthValidator(maxLength: number): ValidatorFn {
3
return (control: AbstractControl): ValidationErrors | null => {
4
return hasValidLength(control.value) && control.value.length > maxLength
5
? { maxlength: { requiredLength: maxLength, actualLength: control.value.length } }
6
: null;
7
};
8
}
9
10
// ---
11
12
function hasValidLength(value: any): boolean {
13
return value != null && typeof value.length === "number";
14
}

As you can see validator checks if a control’s value has a valid length (if it is an object with a length property) and then compares this length with maxLength argument.

We can use this knowledge to create a fake object with a length property. We can get all control’s validators and check if we get the maxLength error for { length: Infinity }.

1
import { AbstractControl, FormControl, Validators } from "@angular/forms";
2
3
function hasMaxLengthValidator(control: AbstractControl): boolean {
4
const validator = control.validator;
5
6
if (validator === null) {
7
return false;
8
}
9
10
const errors = validator(new FormControl({ length: Infinity })) ?? {};
11
return "maxlength" in errors;
12
}
13
14
const titleControl = new FormControl(null, [Validators.maxLength(15)]);
15
const hasMaxLengthValidator = hasMaxLengthValidator(titleControl);
16
console.log(hasMaxLengthValidator); //-> true

Because nothing can be bigger than Infinity we are sure that we cause an error if the validator contains maxLength validator.

Getting maxLength value from the validator

To get information about the maxLength value from the validator first we need to cause an error. In the error details, we have information about the maxLength value and actual value of a control.

1
import { AbstractControl, FormControl, Validators } from "@angular/forms";
2
3
function getMaxLengthFromValidator(control: AbstractControl, fallback: number): number;
4
function getMaxLengthFromValidator(control: AbstractControl): number | undefined;
5
function getMaxLengthFromValidator(control: AbstractControl, fallback?: number): number | undefined {
6
const validatorFn = control.validator;
7
8
if (validatorFn === null) {
9
return fallback;
10
}
11
12
const errors = validatorFn(new FormControl({ length: Infinity }));
13
return errors?.["maxlength"]["requiredLength"] ?? fallback;
14
}
15
16
const titleControl = new FormControl(null, [Validators.max(15)]);
17
const maxLengthValue = getMaxLengthFromValidator(titleControl);
18
console.log(maxLengthValue); //-> 15

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment