Home > OS >  Angular - Combining validations are not working
Angular - Combining validations are not working

Time:03-09

I want to combine a set of validations to a bundle, and then re-use it, but it is not working for me, when I apply the validation bundle the control is always invalid.

validation-bundles.ts - Here I define my validation bundles:

import { ValidationErrors, Validators } from "@angular/forms";

export class ValidationBundles {

    static email(): Array<ValidationErrors | null> {
        return [Validators.required, Validators.email];
    }

    static password(): Array<ValidationErrors | null> {
        return [Validators.required, Validators.minLength(6), Validators.maxLength(50)];
    }

}

login.component.ts - Here I use the validation bundles for exmaple:

this.loginForm = new FormGroup({
      email: new FormControl('', ValidationBundles.email),
      password: new FormControl('', ValidationBundles.password)
    });

login.component.html - Here I define the validation error messages:

<mat-error *ngIf="loginForm.controls['password'].hasError('required')">
    Password is required.
</mat-error>
<mat-error *ngIf="loginForm.controls['password'].hasError('minlength')">
    Mininum length is 6 characters.
</mat-error>
<mat-error *ngIf="loginForm.controls['password'].hasError('maxlength')">
    Maximum length is 50 characters.
</mat-error>

So my questions:

  1. How do I make this work properly?

  2. Can I add more validations to controls when I'm using a bundle? like merging the validations?

  3. Are there any best practices related to this topic?

CodePudding user response:

You are doing everything right, just two minor improvements:

  1. It's array of ValidationFns not ValidationErrors
export class ValidationBundles {

    static email(): Array<ValidatorFn | null> {
        return [Validators.required, Validators.email];
    }

}
  1. You should call ValidationBundles.email like below and you will get what you need: array of ValidationFns
this.loginForm = new FormGroup({
   email: new FormControl('', ValidationBundles.email()),
   password: new FormControl('', ValidationBundles.password())
});
  • Related