[英]Angular validation on form submit
我以如下角度进行验证:
<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>
如何触发表单提交验证? 它仅在输入中按下按键时有效。
我认为这是提交后验证字段的方式。 示例如下:
组件.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>
组件.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();
})
}
}
我找到了解决方案。 我变了:
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.