ifValidator & ifAsyncValidator

Overview

ngx-lift provides utility functions for creating conditional validators in Angular Reactive Forms. Conditional validators allow you to apply specified validator functions based on a given condition. There are two main functions exported: ifValidator for synchronous validators and ifAsyncValidator for asynchronous validators.

ifValidator

The ifValidator function creates a conditional validator that applies the specified validator functions only if the provided condition is met. It takes three parameters: a condition function that determines whether the validators should be applied, the trueValidatorFn representing the validator function or an array of validator functions to be applied when the condition is true, and an optional falseValidatorFn representing the validator function or an array of validator functions to be applied when the condition is false. It returns a validator function that can be used with Angular Reactive Forms.

Here's an example that demonstrates how to use the ifValidator function: Suppose you want to require a reason input and a email input only when the "Sorry" option is selected in a form. The required validator is applied to the text input control only when the "Sorry" option is chosen. The ifValidator function allows you to conditionally apply the validator based on the selected option.

Field required only when you choose Sorry
Field required only when you choose Sorry
import {ifValidator} from 'ngx-lift';

@Component({
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
})
export class IfValidatorComponent {
  validator = ifValidator(
    () => this.form?.controls.choice.value === 'UNLIKE',
    [Validators.required],
    // add mismatch validation functions if needed
  );

  form = new FormGroup({
    choice: new FormControl('', Validators.required),
    email: new FormControl('', [this.validator, Validators.email]),
    reason: new FormControl('', this.validator),
  });

  // updateValueAndValidity whenever the condition is changed.
  changeChoice() {
    this.form.controls.email.updateValueAndValidity();
    this.form.controls.reason.updateValueAndValidity();
  }
}

ifAsyncValidator

ifAsyncValidator shares similarities with ifValidator but differs in that it accepts two parameters: the condition and an AsyncValidation function, designed specifically for handling asynchronous operations.