How to add form validation pattern in Angular 2?

Asked
Active3 hr before
Viewed126 times

9 Answers

angularvalidationpattern
90%

Angular does this by secretly creating special validator directives which have selectors matching required, minlength, maxlength and pattern,,These required, minlength, maxlength and pattern attributes are already in the official HTML specification

Example_snippet/controller/utility/_angular.js/ new FormControl('', Validators. . .
new FormControl('', Validators.required)
load more v
88%

Pattern - Regular expression to match the input values and validate,,Minlength - Minimum number of characters in the field

Example_snippet/controller/utility/_angular.js/ import { Component,Directive. . .
  import {
     Component,
     Directive,
     forwardRef,
     Attribute,
     OnChanges,
     SimpleChanges,
     Input
  } from '@angular/core';
  import {
     NG_VALIDATORS,
     Validator,
     Validators,
     AbstractControl,
     ValidatorFn
  } from '@angular/forms';
  import {
     User
  } from './user';
  @Component({
        moduleId: module.id,
        selector: 'login-form',
        templateUrl: './login-form.component.html',
        styleUrls: ['./login-form.component.css']
     }) export class LoginFormComponent {
        powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];
        model = new User('', '', null, '', '', '');
        submitted = false;
        onSubmit() {
           this.submitted = true;
        }
        newHero() { // this.model = new User('','');    }  }    
load more v
72%

Example-1: Pattern Validation using Reactive Form ,Example-2: Pattern Validation using Template-driven Form ,Pattern Validation with formControlName ,Pattern Validation with formControl

Example_snippet/controller/utility/_angular.js/ my-app | |--src | | | |--a. . .
my - app |
   |
   --src |
   |
   |
   | --app |
   | |
   |
   | | --user.ts |
   | | --user - service.ts |
   | | --reactive - form.component.ts |
   | | --reactive - form.component.html |
   | | --template - driven - form.component.ts |
   | | --template - driven - form.component.html |
   | |
   |
   | | --app.component.ts |
   | | --app.module.ts |
   |
   |
   | --main.ts |
   | --index.html |
   | --styles.css |
   |
   --node_modules |
   --package.json
load more v
65%

Angular Forms Fundamentals , On this Angular forms tutorial we will be using Reactive Forms, , We wanted to create the most complete angular forms tutorial, so we also added advanced custom validators

Example_snippet/controller/utility/_angular.js/ this.username = new FormContro. . .
this.username = new FormControl('agustin', Validators.required);
Step 2 continued with <ion-input type="text" formCon. . .
<ion-input type="text" formControlName="username"></ion-input>
Step 3 continued with this.user_data = new FormGroup. . .
this.user_data = new FormGroup({
   username: new FormControl('agustin', Validators.required),
   city: new FormControl('Montevideo', Validators.required)
});
Step 4 continued with this.user_data = new FormArray. . .
this.user_data = new FormArray({
   new FormControl('agustin', Validators.required),
   new FormControl('Montevideo', Validators.required)
});
Step 5 continued with this.validations_form = this.f. . .
this.validations_form = this.formBuilder.group({
   username: new FormControl('', Validators.required),
   email: new FormControl('', Validators.compose([
      Validators.required,
      Validators.pattern('^[a-zA-Z0-9_.+-][email protected][a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$')
   ]))
});
Step 6 continued with import { Validators, FormBuild. . .
import {
   Validators,
   FormBuilder,
   FormGroup,
   FormControl
} from '@angular/forms';
load more v
75%

As there is actually no validators for regex, you have to write your own, It is a simple function that takes a control in input, and return null if valid or a StringMap if invalid

Example_snippet/controller/utility/_angular.js/ <input [ngControl]="fullName" . . .
<input [ngControl]="fullName" pattern="[a-zA-Z ]*">
Step 2 continued with <form (ngSubmit)="onSubmit(roo. . .
<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'>
Step 3 continued with this.err = { "capacity" :. . .
this.err = {
   "capacity": "too_small"
   "filed_name": "error_name",
   "field2_name": "other_error_name",
   ...
}
Step 4 continued with <input [(ngModel)]='room.capac. . .
<input [(ngModel)]='room.capacity' ...>
<small *ngIf="err.capacity" ...>{{ translate(err.capacity) }}</small>
load more v
40%

The following example shows how to add a pattern validator to an input attached to an ngModel binding,,A directive that adds regex pattern validation to controls marked with the pattern attribute

Example_snippet/controller/utility/_angular.js/ ReactiveFormsModu. . .
      ReactiveFormsModule
load more v
22%

phoneNumber – each phone number must follow a specified pattern, there must be at least one phone number, and the user is allowed to add a new or remove an existing telephone number,, phoneNumber – each phone number must follow a specified pattern, there must be at least one phone number, and the user is allowed to add a new or remove an existing telephone number

Example_snippet/controller/utility/_validation.js/ <form> <div> <label>Name. . .
<form>
   <div>
      <label>Name</label>
      <input type="text" name="name" />
   </div>

   <div>
      <label>Birth Year</label>
      <input type="text" name="birthYear" />
   </div>

   <div>
      <h3>Location</h3>
      <div>
         <label>Country</label>
         <input type="text" name="country" />
      </div>
      <div>
         <label>City</label>
         <input type="text" name="city" />
      </div>
   </div>

   <div>
      <h3>Phone numbers</h3>
      <div>
         <label>Phone number 1</label>
         <input type="text" name="phoneNumber[1]" />
         <button type="button">remove</button>
      </div>
      <button type="button">Add phone number</button>
   </div>

   <button type="submit">Register</button>
   <button type="button">Print to console</button>
</form>
load more v
60%

Furthermore we’re using the pattern HTML validation attribute to for the URL input field:,To implement that constraint we’re adding the HTML validation attributes minlength and maxlength to the input element, ,First of all notice that template variables have been introduced for all three input elements by adding,Angular 2 automatically attached CSS classes to the input elements depending on the state of the control

Example_snippet/controller/utility/_validation.js/ <div class="container"> <h1>. . .
<div class="container">
  <h1>Book Form:</h1>
  <form>
    <div>
      <label for="title">Title</label>
      <input type="text" class="form-control" id="title" required [(ngModel)]="model.title" name="title">
    </div>
    <div>
      <label for="author">Author</label>
      <input type="text" class="form-control" id="author" required [(ngModel)]="model.author" name="author">
    </div>
    <div>
      <label for="url">URL</label>
      <input type="text" class="form-control" id="url" required [(ngModel)]="model.url" name="url">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
  <div>
    <h2>Model:</h2>
    {{ currentBook }}
  </div>
</div>
load more v
48%

Angular 2 Form Validation , Setting Up Our Application ,Model driven or reactive forms, while similar to template driven forms, add an additional layer of complexity and functionality by having you to declare the model of the form in your component class, ,For our next component, we will build a reactive or model driven form

Example_snippet/controller/utility/_validation.js/ npm install -g angular-cli. . .
npm install - g angular - cli
load more v