I want to apply conditional validation on some properties based on some other form values. I have referred some answers Angular2: Conditional required validation, but those are not fulfil my need. Because I have to implement conditional validation in 40+ form(around 30 fields) of my large enterprise application. I don't want write the same code in every component and change the FormControl name. I don't know how this can be achieved via Directive.
if age control valuev is greater than 18 than the license number field is required.
Here's my code:
this.userCustomForm = this.angularFormBuilder.group({ age:['',Validators.required], licenseNo:[''] // Here I want to apply conditional required validation. });
In my application there are some cases where I want set conditional validation based on nested FormGroup
or FormArray
values.
Please guide me, how can I achieve this.
Conditional validation is an available option to select after you choose a validator. As the name implies, if it is selected (and configured correctly) the validation rule will only be ran if the condition is true.
In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.
For me it worked perfectly like this:
this.userCustomForm.get('age').valueChanges.subscribe(val => { if (condition) { this.userCustomForm.controls['licenseNo'].setValidators([Validators.required]); } else { this.userCustomForm.controls['licenseNo'].clearValidators(); } this.userCustomForm.controls['licenseNo'].updateValueAndValidity(); });
You have to updateValueAndValidity of the form for the changes to take effect.
Hope this helps!
My suggestion would be to use dynamic validations.
Subscribe to the changes in the age field of the userCustomForm and whenever the age reaches the condition where license needs to validated, add validators.required dynamically using setValidators()
and clear the validators dynamically using clearValidators()
whenever necessary.
this.userCustomForm.get('age').valueChanges.subscribe(val => { if (condition) { // for setting validations this.userCustomForm.get('licenseNo').setValidators(Validators.required); } if (condition) { // for clearing validations this.userCustomForm.get('licenseNo').clearValidators(); } this.userCustomForm.get('licenseNo').updateValueAndValidity(); });
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