Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do required-if in Angular Reactive Forms?

I have a reactive form and based on the property fooRequired I want to set the field to be required or not.

I can't change that because it set at initial. so what can I do?

fooRequired = false;

form = new FormGroup({
 foo: new FormControl(null, [Validators.required])
});

toggle() { this.fooRequired = !this.fooRequired; }
like image 674
Jon Sud Avatar asked Nov 21 '20 10:11

Jon Sud


People also ask

How do you make a field conditionally required in Angular Reactive form?

Another way to achieve conditional validation in Angular forms would be to write your own group validator. This validator will check the value of the whole group, including the a checkbox. If the checkbox is set, it will require the myEmailField not to be empty.

What is conditional validation?

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.


Video Answer


2 Answers

The following will do the trick:

toggle() {
  this.fooRequired = !this.fooRequired;
  this.form.controls.foo.setValidators(this.fooRequired ? null : [Validators.required]);
  this.form.controls.foo.updateValueAndValidity();
}

Here, based on the fooRequired boolean, the validators are set or removed. Finally, the new form control settings are updated.

like image 105
Nicholas Kurian Avatar answered Oct 23 '22 15:10

Nicholas Kurian


You can use a custom function that gonna be responsible for adding or removing the Validators

export function conditionalValidator(
  predicate: BooleanFn,
  validator: ValidatorFn,
  errorNamespace?: string
): ValidatorFn {
  return formControl => {
    if (!formControl.parent) {
      return null;
    }
    let error = null;
    if (predicate()) {
      error = validator(formControl);
    }
    if (errorNamespace && error) {
      const customError = {};
      customError[errorNamespace] = error;
      error = customError;
    }
    return error;
  };
}

Then you can use it inside you form control:

this.myForm = this.fb.group({
  myEmailField: [
    "",
    [
      // some normal validatiors
      Validators.maxLength(250),
      Validators.minLength(5),
      Validators.pattern(/.+@.+\..+/),
      // custom validation
      conditionalValidator(
        // depends on fooRequired value
        () => this.fooRequired,
        Validators.required,
        "illuminatiError"
      )
    ]
  ]
});

Finally you can toggle the value of fooRequired and see the result:

  toggle() {
    this.fooRequired = !this.fooRequired;
    this.myForm.get("myEmailField").updateValueAndValidity();
  }

Here is a live demo to help you with implementing the above answer

like image 40
Elmehdi Avatar answered Oct 23 '22 17:10

Elmehdi