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
CodePudding user response:
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)
]
]
CodePudding user response:
Use the below command to preview why the problem is occouring.
{{ password.errors | json }}
My version.
<form [formGroup]="form">
<input type="password" placeholder="Password" formControlName="password" />
<!-- {{ password.errors | json }} -->
<div *ngIf="password.errors && password.errors['minlength']">
Minimum characters is
{{
password.errors &&
password.errors['minlength'] &&
password.errors['minlength'].requiredLength
}}
</div>
<div *ngIf="password.errors && password.errors['maxlength']">
Maximum characters
{{
password.errors &&
password.errors['maxlength'] &&
password.errors['maxlength'].requiredLength
}}
</div>
<button>Login</button>
</form>