Html 使用模式 Angular 2 进行输入验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34992630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Input validation with pattern Angular 2
提问by Mathijs Segers
I'm currently writing a simple form in ionic 2 (Angular 2). I was wondering how I'd add a simple regular expressionpattern to the validation:
我目前正在 ionic 2 (Angular 2) 中编写一个简单的表单。我想知道如何向验证添加一个简单的正则表达式模式:
I basically have this:
我基本上有这个:
<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>
The maxlength, minlength & required are being picked up (the button is disabled if conditions not met). Now I want to limit the input to numeric and prefix it with 06 (Dutch phone number with minimum amount of numbers).
maxlength, minlength & required 正在被拾取(如果条件不满足,按钮将被禁用)。现在我想将输入限制为数字并以 06 为前缀(荷兰电话号码的数字最少)。
The pattern is however not picked up in the validation. Can I do it this way, or do I need a code approach?
但是,在验证中不会选择该模式。我可以这样做,还是需要代码方法?
采纳答案by Günter Z?chbauer
Add the pattern to a variable
将模式添加到变量
var pattern=/06([0-9]{8})/;
and bind the attribute to it
并将属性绑定到它
<input type="text"
[(ngModel)]="msisdn"
ngControl="msisdnForm"
required
maxlength="10"
minlength="10"
[pattern]="pattern"
#msisdnForm="ngForm"
>
Seems this PR https://github.com/angular/angular/pull/6623/filesneeds to land first.
似乎这个 PR https://github.com/angular/angular/pull/6623/files需要先登陆。
There is still an open issue https://github.com/angular/angular/issues/7595This prevents pattern
being bound to. The pattern needs to be statically added to the DOM (without binding) to work.
还有一个未解决的问题https://github.com/angular/angular/issues/7595这可以防止pattern
被绑定。该模式需要静态添加到 DOM(无绑定)才能工作。
回答by Kamil Kie?czewski
I put more details (Angular 2.0.8 - 3 March 2016): https://github.com/angular/angular/commit/38cb526
我提供了更多细节(Angular 2.0.8 - 3 March 2016):https: //github.com/angular/angular/commit/38cb526
Example from repo:
来自回购的示例:
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
I tested it, and it worked :) - 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'>
UPDATE September 2017
2017 年 9 月更新
I just wanna to say that currently when I have more experience, I usally use following 'cheap' approach to data validation:
我只想说,目前当我有更多经验时,我通常使用以下“便宜”的方法进行数据验证:
Validation is ONLY on server side (not in angular at all!) and if something is wrong then server (Restful API) return some error code e.g HTTP 400and following json object in response body (which in angular I put to err
variable ):
验证仅在服务器端(根本不是 angular !),如果出现问题,则服务器(Restful API)返回一些错误代码,例如HTTP 400和响应主体中的 json 对象(在 angular 中我将其放入err
变量):
this.err = {
"capacity" : "too_small"
"filed_name" : "error_name",
"field2_name" : "other_error_name",
...
}
(if server return validation error in different format then you can usually easily map it to above structure)
(如果服务器以不同的格式返回验证错误,那么您通常可以轻松地将其映射到上述结构)
In html template i use separate tag (div/span/small etc.)
在 html 模板中,我使用单独的标签(div/span/small 等)
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
As you see, when there is some error in 'capacity' then tag with error translation (to user language) will be visible. This approach have following advantages:
如您所见,当“容量”出现一些错误时,将显示带有错误翻译(到用户语言)的标签。这种方法有以下优点:
- it is very simple
- in angular we not double validation code which is (and must be) in server (in case of regexp validation this can either prevent or complicate ReDoSattacks)
- we have full control on way the error will be shown to user (here as egzample in
<small>
tag) - because in server response we return error_name(instead of direct error message), we can easily change error message (or translate it) by modify only frontend-angular code (or files with translations). So in that case we not need to touch backend/server code.
- 这很简单
- 在 angular 中,我们不会在服务器中重复(并且必须)验证代码(在正则表达式验证的情况下,这可以防止或使ReDoS攻击复杂化)
- 我们可以完全控制向用户显示错误的方式(此处为
<small>
标记中的egzample ) - 因为在服务器响应中我们返回error_name(而不是直接错误消息),我们可以通过仅修改前端角度代码(或带有翻译的文件)轻松更改错误消息(或翻译它)。所以在这种情况下,我们不需要接触后端/服务器代码。
Of course sometimes (if this is needed - eg. retypePassword field which is never send to server) I make exceptions of above approach and make some validation in angular (but use similar "this.err
" mechanism to show errors (so I not use pattern
attribute directly in input
tag but rather I make regexp validation in some component method after user raise proper event like input-change or save) .
当然有时(如果需要的话 - 例如,永远不会发送到服务器的 retypePassword 字段)我对上述方法进行了例外处理,并在 angular 中进行了一些验证(但使用类似的“ this.err
”机制来显示错误(所以我不pattern
直接在input
标记,而是在用户引发适当的事件(如输入更改或保存)后,在某些组件方法中进行正则表达式验证。