Home > Software engineering >  Validation Error in FormGroup level not working
Validation Error in FormGroup level not working

Time:05-03

I have a custom validation in the FormGroup level as defined below:

this.createForm = this.builder.group({
  pass: this.builder.control('',
    [
      Validators.required,
      Validators.minLength(5)
    ]),
  conPass: this.builder.control('',
    [
      Validators.required,
      Validators.minLength(5)
    ]),
}, { validator: [isTheSame('pass', 'conPass')] });

static isTheSame(c1: string, c2: string): ValidatorFn {
   return (form: FormGroup): ValidationErrors | null => {
      const c1Input = form.controls[c1]?.value;
      const c2Input = form.controls[c2]?.value;

      return (c1Input !== c2Input) ? { notTheSame: true } : null;
   };
}

I want to check if the notTheSame is true or not. I used *ngIf="createForm .errors?.notTheSame" and display a text if it returns true. But it doesn't work even notTheSame has a value of "true".

CodePudding user response:

Have you tried this:

createForm.hasError(‘notTheSame’)

Btw, createForm.errors is an array.

CodePudding user response:

Try this I hope it worked for you. Html

<span createForm.get('conPass')?.hasError('notEquivalent') && createForm.get('conPass')?.touched">Password and Confirm password not matched.</span>

CodePudding user response:

You need to set errors on the control level, here I'm attaching code you can use to achieve your desired results.

you can create one function in one service file

service.ts

static MatchPassword(control: AbstractControl) {
    const password = control.get('pass').value;
    const confirmPassword = control.get('conPass').value;
    if (password !== confirmPassword) {
      control.get('conPass').setErrors({ passwordNotMatched: true });
    }
    else {
      return false;
    }
  }

And you can use it in your form during initialization

component.ts

this.createForm = this.builder.group({
  pass: this.builder.control('',
    [
      Validators.required,
      Validators.minLength(5)
    ]),
  conPass: this.builder.control('',
    [
      Validators.required,
      Validators.minLength(5)
    ]),
}, { validator: UtilityService.MatchPassword });

And in your HTML

<p *ngIf="formName['conPass'].errors && formName['conPass'].errors.passwordNotMatched">Password not matched </p>
  • Related