1

I have a condition that if it is true, I want to add a series of validations to some forms, and when the condition is not true, it will remove the validators.

Now, when I add the validator, it works properly, but when I try to remove it, it is not removed properly!!!

//html

<div [formGroup]="form">
    <p-checkbox (onChange)="changeShouldEnter()" name="shouldEnter" [value]="true"
          formControlName="shouldEnter"></p-checkbox>
    <label class="radio-lable mx-2">text</label>
</div>

//typescript

  ngOnInit(): void {    
    this.form = new FormGroup({
      shouldEnter: new FormControl([]),
      storeCategoryId: new FormControl(),
      storeCategoryItemCode: new FormControl(),
    })
  }


  changeShouldEnter() {
    if (this.form.get('shouldEnter').value[0]) {
      this.form.get("storeCategoryId").addValidators(Validators.required)
      this.form.get("storeCategoryItemCode").addValidators(Validators.required)
    } else {
      this.form.get("storeCategoryId").removeValidators(Validators.required)
      this.form.get("storeCategoryItemCode").removeValidators(Validators.required)
    }
    this.cdr.detectChanges();
  }

I even tried this way, but in the end, when I log the form, it is still invalid, and also inside the controls of that form, it says require: true again.

.removeValidators([Validators.required])
//or
.addValidators([])
1
  • Despite that (personal opinion) it's not a good idea remove/add validators, the problem of "requireIf" can be solve by a custom validator, see this SO. See how with this idea you can not take account when change, nor onChange event... Commented Nov 28, 2024 at 7:11

1 Answer 1

1

When you add or remove validators make sure you call updateValueAndValidity, for the changes to be reflected.

From the Docs:

Recalculates the value and validation status of the control.

By default, it also updates the value and validity of its ancestors.

  changeShouldEnter() {
    const shouldEnterCtrl = this.form.get('shouldEnter');
    const storeCategoryIdCtrl = this.form.get('storeCategoryId');
    const storeCategoryItemCodeCtrl = this.form.get('storeCategoryItemCode');
    if (shouldEnterCtrl?.value?.[0]) {
      storeCategoryIdCtrl.addValidators(Validators.required)
      storeCategoryItemCodeCtrl.addValidators(Validators.required)
    } else {
      storeCategoryIdCtrl.removeValidators(Validators.required)
      storeCategoryItemCodeCtrl.removeValidators(Validators.required)
    }
    storeCategoryIdCtrl.updateValueAndValidity(); // <- changed here!
    storeCategoryItemCodeCtrl.updateValueAndValidity(); // <- changed here!
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.