0

Is there any possibility to add new validation functions in form control state by keeping existing already attached validation functions intact?

I hade already added required function from my reducer function.

I have tried below code.

validate(myControl,[email])

But when I add above line, it removes all my previous validations.

Abdullah Qudeer
  • 949
  • 7
  • 24

2 Answers2

0

you should use a formcontrols with formBuilder like this:

this.formBuilder.group({
      title: [this.title, [Validators.required, Validators.email]],

or:

new UntypedFormControl('', {validators: [Validators.required, Validators.email]});
Zerotwelve
  • 2,087
  • 1
  • 9
  • 24
0

Finally I found the solution:

New validation functions can be added to the form control state while preserving existing validations. To achieve this, you need to use the Validators.compose() or Validators.composeAsync() functions provided by Angular.

Here is an example of how you can add a new validation function while still retaining existing functions.

 import { Validators, FormControl } from '@angular/forms';
        
        // Assume you already have a form control with some existing validators
        const myControl = new FormControl('', [
          Validators.required,
          Validators.minLength(3)
        ]);
        
        // Define your new validation function
        const emailValidator = Validators.email;
        
        // Add the new validation function while keeping the existing validators intact
        myControl.setValidators(Validators.compose([myControl.validator, emailValidator]));
        myControl.updateValueAndValidity();
     
Abdullah Qudeer
  • 949
  • 7
  • 24