user3334871
user3334871

Reputation: 1361

Angular 2 - Removing a Validator error

I wrote a function to update Validator rules on an input if a certain option was selected, using this method (the forms are built using FormGroup):

onValueChanged(data : any) {
    let appVIP1 = this.vip1TabForm.get('option1');
    let appVIP2 = this.vip2TabForm.get('option2');
    let appVIP3 = this.vip3TabForm.get('option3');

    //Set required validation if data is 'option3'
    if(data != 'option3') {
        //Due to initialization errors in UI, need to start with the case
        //That there are validations, check to remove them
        appVIP1.setValidators([]);
        appVIP2.setValidators([]);
        appVIP3.setValidators([]);
    }
    else {
        appVIP1.setValidators([Validators.required]);
        appVIP2.setValidators([Validators.required]);
        appVIP3.setValidators([Validators.required]);
    }
}       

And I bind that function call to a click event on radio buttons (I initially used the guide from this answer, but the onChange function didn't bind correctly).

This works great, and if the user selects option 1 or 2, the validations are empty, and won't be triggered. If they select option 3, the validations are shown and submission is stopped. However, I run into the problem where the user submits, sees the error, and goes back to change to option 1 or 2. While the validator is cleared, my form still reads as invalid. I have multiple input fields I am validating, so I can't just set the form to valid if the validator is removed this way. How would I go about doing this? Can I remove the has-error for one particular field in the formgroup?

Upvotes: 5

Views: 5731

Answers (2)

vivekkurien
vivekkurien

Reputation: 1594

Instead of removing and adding validations. It is more simple to enable and disable fields. You need to add the Validators.required for all required fields. And disable the fields which are not required.

onValueChanged(data : any) {
    let appVIP1 = this.vip1TabForm.get('option1');
    let appVIP2 = this.vip2TabForm.get('option2');
    let appVIP3 = this.vip3TabForm.get('option3');

    if(data != 'option3') {
        appVIP1.disable();
        appVIP2.disable();
        appVIP3.disable();
    }
    else {
        appVIP1.enable();
        appVIP2.enable();
        appVIP3.enable();
    }
} 

Upvotes: -1

msanford
msanford

Reputation: 12227

If the correct validators are in place, you can manually call AbstractControl#updateValueAndValidity after they select an option:

this.formBuilder.updateValueAndValidity();

(Where, of course, this.formBuilder is your FormBuilder instance.)

You can also call it on FormElements directly.

This is commonly used to trigger validation after a form element's value has been programmatically changed.

Upvotes: 7

Related Questions