C r e a t i n g C u s t o m Va l i d a t o r s O n R e a c t i v e F o r m s U s i n g A n g u l a r 6 A I M D E K T E C H N O L O G I E S I N C . www.aimdek.com
Introduction • Validating user input for accuracy and completeness helps in improving overall data quality. • Angular and its form package turns up with a Validators class that has some beneficial validators like minLength, maxLength, required and pattern. • However, occasionally if we wish to validate different fields under more complex/custom rules we can make optimum use of custom validator. • Defining custom validators while using Reactive Forms in Angular comes very easy as they are more of regular functions. • One can conveniently generate function for custom validators within the component file in case the validator is not supposed to be used elsewhere. But, herein we will be assuming the re-use and create respective validators in separate files. www.aimdek.com
Step 1: Create a project and add material library Ng new ng6material Cd ng6mateial Ng add @angular/material Ng serve www.aimdek.com
Step 2: Create component called reactiveform.component.ts Ng generate component reactiveform Configure route of reactiveform.component.ts so that we can navigate it at http://localhost:4200/reactive- form www.aimdek.com
Step 3: Create a simple form with a model using Angular material and @angular/form import { Component, OnInit } from '@angular/core'; import{FormBuilder,FormGroup} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './reactiveform.component.html', styleUrls: ['./reactiveform.component.css'] }) export class ReactiveformComponent implements OnInit { complexForm : FormGroup; constructor(fb:FormBuilder) { this.complexForm = fb.group({ userName:””, email:””, passWord:””, }) } ngOnInit() {} submitForm(value: any){ console.log(value); } } Reactiveform.components.ts www.aimdek.com
Step 3: contd. <div class="login-wrapper"> <mat-card> <div style="text-align:center;"> <img src="http://www.aimdek.com/wp- content/uploads/2016/12/height_70px.png"> </div> <form class="example-form" [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)"> <mat-form-field> <input matInput placeholder="Username" [formControl]="complexForm.controls['userName']" /> </mat-form-field> <br> <mat-form-field> <input matInput placeholder="email" [formControl]="complexForm.controls['email']" /> </mat-form-field> <br> <mat-form-field > <input matInput placeholder="Password" [formControl]="complexForm.controls['passWord']" /> </mat-form-field> <br> <button type="submit" mat-raised-button color="primary" align="right">Login</button> </form> </mat-card> </div> Reactiveform.component.html www.aimdek.com
Step 3: contd. This will generate the simple model driven reactive form without in build and custom validation. www.aimdek.com
Step 3: contd. • Now we will add in build validation first and then will go through the custom validation. • For validation we need to import Validators from the @angular/forms and have to add that particular Validators in each field of model. • We are going to use Validators.required and Valodators.email in this demo. • Following snippet shows the usage of build in Validators. www.aimdek.com
Step 4: Generate custom validator for password import { Component, OnInit } from '@angular/core'; import{FormBuilder,FormGroup} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './reactiveform.component.html', styleUrls: ['./reactiveform.component.css'] }) export class ReactiveformComponent implements OnInit { complexForm : FormGroup; constructor(fb:FormBuilder) { this.complexForm = fb.group({ userName:””, email:””, passWord:””, }) } ngOnInit() {} submitForm(value: any){ console.log(value); } } Reactiveform.components.ts www.aimdek.com
Step 3: contd. <div class="login-wrapper"> <mat-card> <div style="text-align:center;"> <img src="http://www.aimdek.com/wp- content/uploads/2016/12/height_70px.png"> </div> <form class="example-form" [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)"> <mat-form-field> <input matInput placeholder="Username" [formControl]="complexForm.controls['userName']" /> </mat-form-field> <br> <mat-form-field> <input matInput placeholder="email" [formControl]="complexForm.controls['email']" /> </mat-form-field> <br> <mat-form-field > <input matInput placeholder="Password" [formControl]="complexForm.controls['passWord']" /> </mat-form-field> <br> <button type="submit" mat-raised-button color="primary" align="right">Login</button> </form> </mat-card> </div> Reactiveform.component.html www.aimdek.com
Step 4: Generate custom validator for password • For this we have to create password.validator.ts manually because angular CLI is not providing this in it’s package. • In this file we have to import abstractValidator which is also part of @angular/form package. • Following is the snnipet code of password.validator.ts import { AbstractControl,Validator } from '@angular/forms'; export function ValidatePassword(control: AbstractControl) { if (!/^(?=.*[A-Za-z])(?=.*d)[A-Za-zd]{4,20}/.test(control.value)) { return { validPassword: true }; } return null; } This code will return boolean if password is valid and return NULL if it is not www.aimdek.com
Step 4: contd. • Now import this validator in reactiveform.components.ts as following – import { ValidatePassword } from '../validators/password.validator’; • Use the ValidatePassword function along with Validator.required in password field of form model as following: – passWord:[null,[Validators.required,ValidatePassword]], • Now we have to use this in reactiveform.component.html inorder to display custom error message for password as following :- – <div class="error" *ngIf="complexForm.get('passWord').errors && complexForm.get('passWord').dirty && complexForm.get('passWord').errors.validPassword"> Password must contain letter and digit. </div> www.aimdek.com
Step 4: contd. And there you have it: how to create a custom validator for Angular Reactive Forms. We at AIMDek cater future-proof front-end development services. www.aimdek.com
INDIA AIMDek Technologies Pvt. Ltd. 203, Shivam Complex, Science City Road, Sola, Ahmedabad, 380060, India Sales: sales@aimdek.com | General: hello@aimdek.com +91 78747 88766 | +1 84474 44423 Canada AIMDek Technologies Inc. 7030 Woodbine Avenue, Suite 500, Markham, Ontario, L3R 6G2, Canada Sales: sales@aimdek.com | General: hello@aimdek.com +1 64724 36116 www.aimdek.com

Creating custom Validators on Reactive Forms using Angular 6

  • 1.
    C r ea t i n g C u s t o m Va l i d a t o r s O n R e a c t i v e F o r m s U s i n g A n g u l a r 6 A I M D E K T E C H N O L O G I E S I N C . www.aimdek.com
  • 2.
    Introduction • Validating userinput for accuracy and completeness helps in improving overall data quality. • Angular and its form package turns up with a Validators class that has some beneficial validators like minLength, maxLength, required and pattern. • However, occasionally if we wish to validate different fields under more complex/custom rules we can make optimum use of custom validator. • Defining custom validators while using Reactive Forms in Angular comes very easy as they are more of regular functions. • One can conveniently generate function for custom validators within the component file in case the validator is not supposed to be used elsewhere. But, herein we will be assuming the re-use and create respective validators in separate files. www.aimdek.com
  • 3.
    Step 1: Createa project and add material library Ng new ng6material Cd ng6mateial Ng add @angular/material Ng serve www.aimdek.com
  • 4.
    Step 2: Createcomponent called reactiveform.component.ts Ng generate component reactiveform Configure route of reactiveform.component.ts so that we can navigate it at http://localhost:4200/reactive- form www.aimdek.com
  • 5.
    Step 3: Createa simple form with a model using Angular material and @angular/form import { Component, OnInit } from '@angular/core'; import{FormBuilder,FormGroup} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './reactiveform.component.html', styleUrls: ['./reactiveform.component.css'] }) export class ReactiveformComponent implements OnInit { complexForm : FormGroup; constructor(fb:FormBuilder) { this.complexForm = fb.group({ userName:””, email:””, passWord:””, }) } ngOnInit() {} submitForm(value: any){ console.log(value); } } Reactiveform.components.ts www.aimdek.com
  • 6.
    Step 3: contd. <divclass="login-wrapper"> <mat-card> <div style="text-align:center;"> <img src="http://www.aimdek.com/wp- content/uploads/2016/12/height_70px.png"> </div> <form class="example-form" [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)"> <mat-form-field> <input matInput placeholder="Username" [formControl]="complexForm.controls['userName']" /> </mat-form-field> <br> <mat-form-field> <input matInput placeholder="email" [formControl]="complexForm.controls['email']" /> </mat-form-field> <br> <mat-form-field > <input matInput placeholder="Password" [formControl]="complexForm.controls['passWord']" /> </mat-form-field> <br> <button type="submit" mat-raised-button color="primary" align="right">Login</button> </form> </mat-card> </div> Reactiveform.component.html www.aimdek.com
  • 7.
    Step 3: contd. Thiswill generate the simple model driven reactive form without in build and custom validation. www.aimdek.com
  • 8.
    Step 3: contd. •Now we will add in build validation first and then will go through the custom validation. • For validation we need to import Validators from the @angular/forms and have to add that particular Validators in each field of model. • We are going to use Validators.required and Valodators.email in this demo. • Following snippet shows the usage of build in Validators. www.aimdek.com
  • 9.
    Step 4: Generatecustom validator for password import { Component, OnInit } from '@angular/core'; import{FormBuilder,FormGroup} from '@angular/forms'; @Component({ selector: 'app-login', templateUrl: './reactiveform.component.html', styleUrls: ['./reactiveform.component.css'] }) export class ReactiveformComponent implements OnInit { complexForm : FormGroup; constructor(fb:FormBuilder) { this.complexForm = fb.group({ userName:””, email:””, passWord:””, }) } ngOnInit() {} submitForm(value: any){ console.log(value); } } Reactiveform.components.ts www.aimdek.com
  • 10.
    Step 3: contd. <divclass="login-wrapper"> <mat-card> <div style="text-align:center;"> <img src="http://www.aimdek.com/wp- content/uploads/2016/12/height_70px.png"> </div> <form class="example-form" [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)"> <mat-form-field> <input matInput placeholder="Username" [formControl]="complexForm.controls['userName']" /> </mat-form-field> <br> <mat-form-field> <input matInput placeholder="email" [formControl]="complexForm.controls['email']" /> </mat-form-field> <br> <mat-form-field > <input matInput placeholder="Password" [formControl]="complexForm.controls['passWord']" /> </mat-form-field> <br> <button type="submit" mat-raised-button color="primary" align="right">Login</button> </form> </mat-card> </div> Reactiveform.component.html www.aimdek.com
  • 11.
    Step 4: Generatecustom validator for password • For this we have to create password.validator.ts manually because angular CLI is not providing this in it’s package. • In this file we have to import abstractValidator which is also part of @angular/form package. • Following is the snnipet code of password.validator.ts import { AbstractControl,Validator } from '@angular/forms'; export function ValidatePassword(control: AbstractControl) { if (!/^(?=.*[A-Za-z])(?=.*d)[A-Za-zd]{4,20}/.test(control.value)) { return { validPassword: true }; } return null; } This code will return boolean if password is valid and return NULL if it is not www.aimdek.com
  • 12.
    Step 4: contd. •Now import this validator in reactiveform.components.ts as following – import { ValidatePassword } from '../validators/password.validator’; • Use the ValidatePassword function along with Validator.required in password field of form model as following: – passWord:[null,[Validators.required,ValidatePassword]], • Now we have to use this in reactiveform.component.html inorder to display custom error message for password as following :- – <div class="error" *ngIf="complexForm.get('passWord').errors && complexForm.get('passWord').dirty && complexForm.get('passWord').errors.validPassword"> Password must contain letter and digit. </div> www.aimdek.com
  • 13.
    Step 4: contd. Andthere you have it: how to create a custom validator for Angular Reactive Forms. We at AIMDek cater future-proof front-end development services. www.aimdek.com
  • 14.
    INDIA AIMDek Technologies Pvt.Ltd. 203, Shivam Complex, Science City Road, Sola, Ahmedabad, 380060, India Sales: sales@aimdek.com | General: hello@aimdek.com +91 78747 88766 | +1 84474 44423 Canada AIMDek Technologies Inc. 7030 Woodbine Avenue, Suite 500, Markham, Ontario, L3R 6G2, Canada Sales: sales@aimdek.com | General: hello@aimdek.com +1 64724 36116 www.aimdek.com