Angular-Form Validator无法显示错误消息



我设置了表单验证。我想要消息";最小字符4〃;如果字符数小于4或如果字符数大于8则出现消息"0";最大字符数为8";出现。

应用程序组件.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>

为什么它不起作用?我是根据Angular文档制作的。https://angular.io/guide/form-validation#validating-以反应形式输入

https://github.com/MyTestPerson/form-validator/tree/master/src/app

Validators.minLength()返回带有minlength属性的错误

返回

ValidatorFn:一个验证器函数,如果验证检查失败,则返回带有minlength属性的错误映射,否则为null。

password.errors?.['minlength']

Validators.maxLength()返回具有maxlength属性的错误。

返回

ValidatorFn:一个验证器函数,如果验证检查失败,则返回带有maxlength属性的错误映射,否则为null。

password.errors?.['maxlength']

示例StackBlitz演示


FYI,表单控制的验证器可以简化为:

password: ['',
[
Validators.minLength(4),
Validators.maxLength(8)
]
]

使用以下命令预览出现问题的原因。

{{ password.errors | json }} 

我的版本。

<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>

堆叠式

相关内容

最新更新