现在,您不需要使用FormBuilder
以及所有这些复杂的验证角度的东西。我从中提供了更多详细信息(Angular 2.0.8 - 2016 年 3 月 3 日):https://github.com/angular/angular/commit/38cb526 https://github.com/angular/angular/commit/38cb526
存储库中的示例:
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
我测试了它并且它有效:) - 这是我的代码:
<form (ngSubmit)="onSubmit(room)" #roomForm='ngForm' >
...
<input
id='room-capacity'
type="text"
class="form-control"
[(ngModel)]='room.capacity'
ngControl="capacity"
required
pattern="[0-9]+"
#capacity='ngForm'>
替代方法(2017 年 6 月更新)
验证仅在服务器端进行。如果出现问题,服务器会返回错误代码,例如HTTP 400 https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#400以及响应正文中的以下 json 对象(作为示例):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
在 html 模板中,我使用单独的标签(div/span/small 等)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
如果“容量”中出现错误,则带有消息翻译的标签将可见。这种方法有以下优点:
- 很简单
- 避免后端验证代码在前端重复(对于正则表达式验证,这可能会阻止或复杂化ReDoS https://en.wikipedia.org/wiki/ReDoS攻击)
- 控制错误的显示方式(例如
<small>
tag)
- 后端返回错误名称这很容易在前端翻译成正确的语言
当然,有时如果前端需要验证(例如retypePassword
注册时的字段永远不会发送到服务器)。