1 回答

TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
可以的。簡(jiǎn)略代碼如下:
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': '請(qǐng)輸入用戶名',
'maxlength': '用戶名不能超過20位'
},
'password': {
'required': '請(qǐng)輸入密碼',
'minlength': '密碼至少6位',
'maxlength': '密碼必須小于16位',
'pattern': '密碼需要包含大小寫和數(shù)字'
}
};
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()); // 監(jiān)聽每次輸入內(nèi)容,獲得錯(cuò)誤信息
}
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] + ' ';
}
}
}
添加回答
舉報(bào)