我强烈建议你使用ReactiveForms
,而不是作为TemplateDrivenForms
他们真的很好管理的验证模式和消息。
HTML片段例如:
<form novalidate [formGroup]="user" (ngSubmit)="onSubmit()">
<div formGroupName="account">
<md-input-container>
<input md-input type="text" placeholder="{{'USER.EMAIL' | translate}} *" formControlName="email" autocomplete="off">
<md-hint class="error" *ngIf="user.get('account.email').hasError('required') && user.get('account.email').touched">
{{'VALIDATOR.EMAIL_RQ' | translate}}
</md-hint>
<md-hint class="error" *ngIf="user.get('account.email').hasError('pattern') && user.get('account.email').touched">
{{'VALIDATOR.WRONG_EMAIL' | translate}}
</md-hint>
</md-input-container>
<md-input-container>
<input md-input type="password" placeholder="{{'USER.PASSWORD' | translate}} *" minlength="6" formControlName="password" autocomplete="off">
<md-hint class="error" *ngIf="user.get('account.password').hasError('required') && user.get('account.password').touched">
{{'VALIDATOR.PWD_RQ' | translate}}
</md-hint>
</md-input-container>
</div>
<button md-raised-button [disabled]="!user.valid || submitted" color="accent" type="submit" class="submit-button">
{{'LOGIN.BUTTON' | translate}}
</button>
</form>
此HTML示例示出了具有验证一个登录表单。请注意0元素如何仅在表单在特定字段上具有验证错误时才显示。
你实际上可以设置一个界面来匹配你的ReactiveForm
。 这里是链接到例如接口:
export interface Account {
account: {
email: string;
password: string;
}
}
打字稿例子片断:
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { EmailRegex } from 'app/shared/shared.interface'; // Imported regex for validator
...
user: FormGroup;
ngOnInit() {
...
// Init your reactive form
this.user = this.formBuilder.group({
account: this.formBuilder.group({
email: ['', [Validators.required, Validators.pattern(EmailRegex)]],
password: ['', Validators.required]
})
});
}
请注意如何表单组比赛接口。另外,如果需要,您可以在那里设置表单值,但正如您所看到的,我的域email
和password
设置为空字符串值。 请注意,您还可以在链接到该字段的阵列中添加尽可能多的验证器。
然后,您可以从您的主FormGroup
访问表单值上submit()
直接:
this.user.value.account.email
如果这个例子还不够好,我强烈建议你阅读托德座右铭对ReactiveForms
指南,是真的很好解释:
https://toddmotto.com/angular-2-forms-reactive
请注意,我用的是https://material.angular.io/库,因此我有'md-name' html元素的原因。所以你的'md-hint'可能会是一个简单的'div' –
谢谢,但我需要验证TemplateDrivenForms,因为我已经在我的项目中有这个。 – playerone
这只是一种不同的形式,但它可以让你做出你想要的工作。你必须改变这种形式,即使在你的应用中有其他模板驱动的表单,它也会作为一种魅力工作。 –