How to get the max value from FormControl’s validator
Unfortunately `hasValidator` does not work well with validators created dynamically like `Validator.max` but there is a solution that allows getting information about max value anyway.
Let’s create a simple FormControl with max validator.
To check if the control has some validator we can use the hasValidator method
but it does not work correctly for Validators.max(18) because calling Validators.max(18)
creates another reference and the implementation of hasValidator check validators by reference.
Checking if a control has a max validator without hasValidator
To check if the control has a max validator we can use knowledge about numbers.
We can get all control’s validators and check if we get the max error for Infinity.
Because nothing can be bigger than Infinity we are sure that we cause an error if the validator contains max validator.
Getting max value from the validator
To get information about the max value from the validator first we need to cause an error.
In the error details, we have information about the max value and actual value of a control.
We have to write errors['max']['max'] because first max is the error
key and the second max is the value passed as the argument of Validators.max function.
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.