Validating input with an Angular 2 pattern

I am currently writing a simple form in Ionic 2 (Angular 2). I was wondering how to add a simple regex pattern to validation:

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>

Increases the maximum length, minimum length and required (the button is disabled if the conditions are not met). Now I want to limit the input to numerical and prefix it with 06 (a Dutch phone number with a minimum number of numbers).

However, the template is not matched during validation. Can I do it this way, or do I need a code approach?

+4
source share
2 answers

Add a template to the variable

var pattern=/06([0-9]{8})/;

 <input type="text"
               [(ngModel)]="msisdn"
               ngControl="msisdnForm"
               required
               maxlength="10"
               minlength="10"
               [pattern]="pattern"
               #msisdnForm="ngForm"
        >

, PR https://github.com/angular/angular/pull/6623/files .

- https://github.com/angular/angular/issues/7595 pattern. DOM ( ) .

+4

(AngularJS 2.0.8 - 3 2016 ): https://github.com/angular/angular/commit/38cb526

:

<input [ngControl]="fullName" pattern="[a-zA-Z ]*">

, :) - :

<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

, , , "" :

( angular !), - , (Restful API) , HTTP 400 json ( angular err):

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

( , )

html- (div/span/small ..)

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

, 'capacity', ( ). :

  • angular , ( ) ( , ReDoS)
  • , ( egzample <small>)
  • error_name ( ), ( ), frontend- angular ( ). /.

, ( - , retypePassword, ), angular ( this.err ( pattern input, , , , ).

+7

Source: https://habr.com/ru/post/1625828/


All Articles