Issue
I set up form validation. I want the message "Minimum characters 4" to appear if the number of characters is less than four or if the number of characters is more than eight then the message "Maximum characters 8" appears.
app.component.ts
export class AppComponent {
constructor(private fb: FormBuilder) {}
form = this.fb.group({
password: ['', {
validators: [
Validators.minLength(4),
Validators.maxLength(8)
]
}]
});
get password() {
return this.form.controls['password'];
}
}
app.component.html
<form [formGroup]="form">
<input type="password" placeholder="Password" formControlName="password">
<div *ngIf="password.errors?.['minLength']"> Minimum characters </div>
<div *ngIf="password.errors?.['maxLength']"> Maximum characters </div>
<button> Login </button>
</form>
Why does not it work? I made it from the Angular documentation. https://angular.io/guide/form-validation#validating-input-in-reactive-forms
https://github.com/MyTestPerson/form-validator/tree/master/src/app
Solution
Validators.minLength() return the error with minlength property
Returns
ValidatorFn: A validator function that returns an error map with the minlength property if the validation check fails, otherwise null.
password.errors?.['minlength']
and
Validators.maxLength() return the error with maxlength property.
Returns
ValidatorFn: A validator function that returns an error map with the maxlength property if the validation check fails, otherwise null.
password.errors?.['maxlength']
FYI, the validators for the form control can be simplified with:
password: ['',
[
Validators.minLength(4),
Validators.maxLength(8)
]
]
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.