Mat*_*ers 8 regex validation html5 ionic2 angular
我目前正在写一个离子2(Angular 2)的简单形式.我想知道如何在验证中添加一个简单的正则表达式模式:
我基本上有这个:
<form>
<ion-input stacked-label>
<ion-label>{{label.msisdn}}</ion-label>
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
pattern="06([0-9]{8})"
#msisdnForm="ngForm"
>
</ion-input>
<button [disabled]="!msisdnForm.valid" block (click)="requestActivationCode()">
{{label.requestActivationCode}}
</button>
</form>
Run Code Online (Sandbox Code Playgroud)
拾取最大长度,最小长度和所需数量(如果不满足条件,则禁用该按钮).现在我想将输入限制为数字,并以06为前缀(荷兰电话号码,最小数量).
但是,在验证中未获取该模式.我可以这样做,还是需要代码方法?
将模式添加到变量
var pattern=/06([0-9]{8})/;
Run Code Online (Sandbox Code Playgroud)
并将属性绑定到它
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
[pattern]="pattern"
#msisdnForm="ngForm"
>
Run Code Online (Sandbox Code Playgroud)
似乎这个PR https://github.com/angular/angular/pull/6623/files需要先登陆.
还有一个未解决的问题https://github.com/angular/angular/issues/7595
这可以防止pattern被绑定.需要将模式静态添加到DOM(无绑定)才能工作.
我提出了更多细节(AngularJS 2.0.8 - 2016年3月3日):https: //github.com/angular/angular/commit/38cb526
回购示例:
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
Run Code Online (Sandbox Code Playgroud)
我测试了它,它工作:) - 这是我的代码:
<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'>
Run Code Online (Sandbox Code Playgroud)
2017年9月更新
我只是想说,目前当我有更多经验时,我通常使用"廉价"方法进行数据验证:
验证仅在服务器端(根本不是角度!),如果出现问题,那么服务器(Restful API)会返回一些错误代码,例如HTTP 400,并在响应正文中跟随json对象(在角度I放入err变量):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
Run Code Online (Sandbox Code Playgroud)
(如果服务器以不同的格式返回验证错误,那么您通常可以轻松地将其映射到上面的结构)
在html模板中我使用单独的标签(div/span/small等)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
Run Code Online (Sandbox Code Playgroud)
如您所见,当'capacity'中存在一些错误时,将显示带有错误翻译(用户语言)的标记.这种方法有以下优点:
<small>标签中的egzample )当然有时候(如果需要的话 - 例如,永远不会发送到服务器的retypePassword字段)我做了上述方法的例外,并在角度进行了一些验证(但使用类似的" this.err"机制来显示错误(所以我不pattern直接使用属性)input标签,而是在用户引发输入更改或保存等适当事件后,在某些组件方法中进行regexp验证.