Maximum value validator with dynamic value
Update for your edited question:
Use this:
value: ['', [
Validators.required,
Validators.min(1),
(control: AbstractControl) => Validators.max(this.totalAmount)(control)
]]
You can achieve that by using this syntax:
(control: AbstractControl) => Validators.max(this.totalAmount)(control)
Why?
- When you supply
Validators.max(this.totalAmount)
, it creates a validation function with the given parameter (current value ofthis.totalAmount
) then assign it to the form control. - When you use fat arrow function, what is assigned to the form control is the fat arrow definition itself. Everytime the fat arrow function is invoked (during validity checking), it revaluates the
Validators.max(this.totalAmount)
and create new validation function with the current value ofthis.totalAmount
, thus makes it dynamic.
Just a little addition to the previous answers, when you need to set the value of the validator of a formControl of another formControl of the same form, you can init the form without validators, and register them after, just like this:
const form: FormGroup = this._fb.group({
from: [''],
to: ['']
});
form.controls.from.setValidators([
Validators.required,
(control: AbstractControl) => Validators.max(this.form.controls.to.value)(control)
]);
And the same goes for to
.