我在角度验证如下:
<form #f="ngForm" (ngSubmit)="save(f.value, f.valid)" novalidate >
<input type="email" name="txtEmail" id="txtEmail" required
[(ngModel)]="model.txtEmail" #txtEmail="ngModel">
<div class="msgerror" *ngIf="txtEmail.invalid && (txtEmail.dirty || txtEmail.touched) ">E-Mail invalid</div>
<button type="submit">Submit</button>
</form>
如何在表单提交时触发验证?它仅在按下输入键时才有效。
答案 0 :(得分:1)
我认为这是在提交后验证字段的方式。示例如下:
<强> component.html 强>
<form name="editForm" role="form" novalidate (ngSubmit)="save(editForm)" #editForm="ngForm" class="form-horizontal">
<input type="text" class="form-control" [(ngModel)]="model.txtEmail" name="txtEmail" id="txtEmail" required>
<div [hidden]="!(editForm.controls.txtEmail?.dirty && editForm.controls.txtEmail?.invalid)">
<small class="form-text text-danger"
[hidden]="!editForm.controls.txtEmail?.errors?.required">
This field is required.
</small>
</div>
<button type="submit" type="submit">Save</button>
</form>
<强> component.ts 强>
import { NgForm } from '@angular/forms';
export class AppComponent {
private model: any = {};
private editForm: NgForm;
save(form: NgForm) {
this.editForm = form;
Object.keys(this.editForm.controls).forEach(key => {
this.editForm.controls[key].markAsDirty();
})
}
}
答案 1 :(得分:0)
我找到了解决方案。我改变了:
<div class="msgerror" *ngIf="txtEmail.invalid && (txtEmail.dirty || txtEmail.touched) ">bitte die E-Mail Adresse angeben! </div>
到
<div [hidden]="txtEmail.valid || (txtEmail.pristine && !f.submitted)" class="text-danger">bitte die E-Mail Adresse angeben! </div>