我想在angular2中验证表单.我学习了一些文档,它将被定义如下:
<form [ngFormModel]="form"> <input type="text" ngControl="username" /> <p *ngIf="username.pending">Fetching data from the server...</p> <div *ngIf="username.dirty && !username.valid && !username.pending"> <p *ngIf="username.errors.required">Username is required.</p> <p *ngIf="username.errors.startsWithNumber">Your username can't start with a number</p> <p *ngIf="username.errors.usernaMetaken">This username is taken</p> </div> <button (click)="submitData()" [disabled]="!form.valid" class="btn btn-primary">Sumbit data</button> </form>
constructor(private builder: FormBuilder) { this.username = new Control( "",Validators.compose([Validators.required,UsernameValidator.startsWithNumber]),UsernameValidator.usernaMetaken ); this.form = builder.group({ username: this.username }); }
对于每个输入,我需要定义许多错误消息.我认为这不好.
我想像jquery.validate,我只是定义输入,错误消息将自动渲染,像这样
<input required name="username" maxlength='8' pattern="^(?!\s|.*\s$).*$" ...>@H_301_10@
@H_301_10@
要减少代码,一种方法可能是编写组件.
这将处理所有条件检查和错误消息
This guy did a nice job here of implementing and explaining it.
带Component的HTML看起来像这样
<input ngControl="email" id="email" /> <control-messages control="email"></control-messages>
并且所有脏工作都将进入控制消息组件.
@H_301_10@ 原文链接:https://www.f2er.com/angularjs/141126.html