I am developing reset password form, where I want to validate the password field with some validation. Validations are mentioned below:
Here is my component code as per need.
this.userForm = this.appFormBuilder.group({
password:['',[Validators.pattern(/[a-z]/),Validators.pattern(/[A-Z]/), Validators.min(8),Validators.max(10)]]
})
I want to show error message of respective condition has been failed on UI, But I am getting pattern error object on UI. How can I show error message of respective condition failed. Here is my Html code:
<div [formGroup]="userForm">
<input type="text" formControlName="password" />
{{userForm.controls.password.errors | json}}
</div>
You can create an function which will validate the form control
export function validatPatternMatch(control: AbstractControl): {[key: string]: boolean} {
const age = control.value;
if(condition1 fails){
return {lowercase: true};
}else if(condition2 fails){
return {uppercase: true};
}
return null; // no error
}
this.userForm = this.appFormBuilder.group({
password:['',[validatPatternMatch]]
});
<div [formGroup]="userForm">
<input type="text" formControlName="password" />
{{userForm.controls.password.errors. pattern}}
<div *ngIf="f.firstName.errors?.lowercase">One Lowercase</div>
<div *ngIf="f.firstName.errors?.uppercase">One Uppercase</div>
You can get the error message from specific validation name.
Ex :
<div [formGroup]="userForm">
<input type="text" formControlName="password" />
{{userForm.controls.password.errors. pattern}}
<div *ngIf="f.firstName.errors.min">Min length should be 8</div>
<div *ngIf="f.firstName.errors.max">Min length should be 10</div>
<div *ngIf="f.firstName.errors.pattern">Pasword format must be xyz format</div>
</div>
Multiple errors with the same error (e.g.: 'pattern') will be override.
So if you want to use same pattern validator you should write the custom validator.
regexValidator(regex: RegExp, error: ValidationErrors): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
if (!control.value) {
return null;
}
const valid = regex.test(control.value);
return valid ? null : error;
};
}
-
this.regexValidator(new RegExp('[a-z]'), {'smallLetters': ''}),
this.regexValidator(new RegExp('[A-Z]'), {'capitalLetters': ''})
html
<div *ngIf="r.firstName.hasError('precision')">It must have small letter </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With