如何angular2添加表单验证模式 [英] How to add form validation pattern in angular2
问题描述
说,如果我有一个需要验证的开始和输入结束一个简单的形式是不占空间。
Say if I have an a simple form that needs to validate the beginning and the end of the input is not space.
在HTML5中,我将做到这一点:<输入类型=文本模式=^ | * $(\\ S * \\ S $?!)。>
In html5, I will do this:
<input type="text" pattern="^(?!\s|.*\s$).*$">
.
什么是验证模式,在新Angular2 ngControl指令正确的属性?正式公测API仍然缺乏文档在这个问题上。
What is the right property for validation pattern in the new Angular2 ngControl directive? The official Beta API is still lack of documentation on this issue.
更新:
原来, 控制类
是正则表达式验证模式添加到的形式是最可行的方式
。
下面是一个<一个href=\"https://github.com/zhenyanghua/angular2-forms/blob/custom_validation/app/hero-form.component.ts\">example这增加了一个自定义验证到在的测试版的例如,从官方的开发者指南。
Here is an example that added a custom validator to the the beta example from the official Developer Guides.
关键是要构建一个 FormBuilder
,并将其分配给 ngFormModel
属性>&LT;形式的方式&gt; 元素
The key is to construct a FormBuilder
and assign it to the ngFormModel
property of the <form>
element.
推荐答案
现在,你不需要使用 FormBuilder
而这一切复杂的valiation角的东西。我把更多的信息从这里(角2.0.8 - 3march2016):
https://github.com/angular/angular/commit/38cb526
Now, you don't need to use FormBuilder
and all this complicated valiation angular stuff. I put more details from this (Angular 2.0.8 - 3march2016):
https://github.com/angular/angular/commit/38cb526
从回购例如:
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
我测试它和它的作品:) - 这里是我的code:
I test it and it works :) - here is my code:
<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'>
这篇关于如何angular2添加表单验证模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!