1 回答

TA贡献1798条经验 获得超3个赞
可以的。简略代码如下:
html:
<input type="text" formControlName="account">
<div *ngIf="formErrors.account" class="alert alert-danger">{{ formErrors.account }}</div>
<input type="password" formControlName="password">
<div *ngIf="formErrors.password" class="alert alert-danger">{{ formErrors.password }}</div>
ts:
editForm: FormGroup;
formErrors = {
'account': '',
'password': ''
};
validationMessages = {
'account': {
'required': '请输入用户名',
'maxlength': '用户名不能超过20位'
},
'password': {
'required': '请输入密码',
'minlength': '密码至少6位',
'maxlength': '密码必须小于16位',
'pattern': '密码需要包含大小写和数字'
}
};
ngOnInit() {
this.editForm = new FormGroup({
account: new FormControl('', [Validators.required, Validators.maxLength(20)]),
password: new FormControl('', [
Validators.minLength(6),
Validators.maxLength(16),
Validators.required,
Validators.pattern('^(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z])[0-9a-zA-Z]{6,16}$')
])
});
this.editForm.valueChanges.subscribe(() => this.onValueChanged()); // 监听每次输入内容,获得错误信息
}
onValueChanged() {
for (const item in this.formErrors) {
this.formErrors[item] = '';
for (const key in this.editForm.get(item).errors) {
this.formErrors[item] += this.validationMessages[item][key] + ' ';
}
}
}
添加回答
举报