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.
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'>
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:
<small>
tag)Of course sometimes I make exception if validation is needed on frontend side (e.g. retypePassword
field on registration is never send to server).