如何在Angular 2中添加表单验证模式? [英] How to add form validation pattern in Angular 2?

查看:88
本文介绍了如何在Angular 2中添加表单验证模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表单,需要验证输入的开头和结尾是否不是空格.

I have a simple form that needs to validate if the beginning and the end of the input is not space.

在HTML5中,我将这样做:

In HTML5, I will do this:

<input type="text" pattern="^(?!\s|.*\s$).*$">

新的Angular 2 ngControl指令中的验证模式正确的属性是什么?官方Beta API仍然缺少有关此问题的文档.

What is the right property for validation pattern in the new Angular 2 ngControl directive? The official Beta API is still lacking documentation on this issue.

推荐答案

现在,您无需使用FormBuilder以及所有这些复杂的价差角度材料.我从中提出了更多细节(Angular 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 ]*">

我对其进行了测试,并且可以正常工作:)-这是我的代码:

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'>

替代方法(2017年6月更新)

仅在服务器端进行验证.如果出现问题,则服务器返回错误代码,例如 HTTP 400 并响应以下json对象正文(例如):

Alternative approach (UPDATE June 2017)

Validation is ONLY on server side. If something is wrong then server return error code e.g HTTP 400 and following json object in response body (as example):

this.err = { 
    "capacity" : "too_small"
    "filed_name" : "error_name", 
    "field2_name" : "other_error_name",
    ... 
}

在html模板中,我使用单独的标签(div/span/small等)

In html template I use separate tag (div/span/small etc.)

<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>

如果容量"中的错误,则显示带有味精翻译的标签.这种方法具有以下优点:

If in 'capacity' is error then tag with msg translation will be visible. This approach have following advantages:

  • 这很简单
  • 避免在前端上进行后端验证代码重复(对于正则表达式验证,这可能会阻止或使 ReDoS 复杂化>攻击)
  • 控制显示错误的方式(例如<small>标签)
  • 后端返回 error_name ,可以很容易地在前端将其翻译成正确的语言
  • it is very simple
  • avoid backend validation code duplication on frontend (for regexp validation this can either prevent or complicate ReDoS attacks)
  • control on way the error is shown (e.g. <small> tag)
  • backend return error_name which is easy to translate to proper language in frontend

当然,有时候我会在前端需要验证的情况下做出例外处理(例如,注册中的retypePassword字段永远不会发送到服务器).

Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword field on registration is never send to server).

这篇关于如何在Angular 2中添加表单验证模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆