【发布时间】:2018-05-08 23:04:26
【问题描述】:
我正在处理此表单并希望在输入时进行验证。 当前的行为是我选择输入,输入,当我点击其他站点时,它会显示错误。我认为当我设置控制时它发生的错误,有效和肮脏,但我无法弄清楚。
打字稿
buildForm(): void {
this.userForm = this.fb.group({
'email': ['', [
Validators.required,
Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$')
]
],
'password': ['', [
Validators.required,
Validators.minLength(6),
Validators.maxLength(25)
]
],
});
this.userForm.valueChanges.subscribe(data => this.onValueChanged(data));
}
onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.invalid && control.dirty) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + ' ';
}
}
}
}
函数 onValueChanged() 改变这个对象
formErrors = {
'email': '',
'password': ''
};
这个对象有验证信息。
validationMessages = {
'email': {
'required': 'Email is required',
'pattern': 'Email is invalid'
},
'password': {
'required': 'Password is required',
'minlength': 'Debe tener 6 caracteres como mínimo',
'maxlength': 'Password cannot be more than 40 characters long.',
}
};
HTML
<mat-form-field class="example-full-width">
<input matInput placeholder="Email" formControlName="email" required>
<mat-error *ngIf="formErrors.email" align="start" class="form__error">
{{ formErrors.email }}
</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<input matInput placeholder="Password" type="password" formControlName="password" required>
<mat-error *ngIf="formErrors.password" align="start" class="form__error">
{{ formErrors.password }}
</mat-error>
</mat-form-field>
【问题讨论】:
标签: angular angular-material angular-reactive-forms angular-forms