'Angular - Combining validations are not working
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:
How do I make this work properly?
Can I add more validations to controls when I'm using a bundle? like merging the validations?
Are there any best practices related to this topic?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
