Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add form validation pattern in Angular 2?

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

In HTML5, I will do this:

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

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.

like image 810
Downhillski Avatar asked Jan 01 '16 19:01

Downhillski


1 Answers

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

Example from repo :

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

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",     ...  } 

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:

  • 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

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

like image 197
Kamil Kiełczewski Avatar answered Oct 06 '22 03:10

Kamil Kiełczewski