SlideShare a Scribd company logo
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

More Related Content

What's hot

Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
Eyal Vardi
 
JSON Web Tokens
JSON Web TokensJSON Web Tokens
JSON Web Tokens
Ivan Rosolen
 
Json Web Token - JWT
Json Web Token - JWTJson Web Token - JWT
Json Web Token - JWT
Prashant Walke
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
Nir Kaufman
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
Kanda Runapongsa Saikaew
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced Routing
Laurent Duveau
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT Exploitation
AkshaeyBhosale
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
Rodolfo Assis (Brute)
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
Sultan Ahmed
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
Sandi Barr
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
Vladimir Dzhuvinov
 
Json web token
Json web tokenJson web token
Json web token
Mayank Patel
 
Demystifying OAuth 2.0
Demystifying OAuth 2.0Demystifying OAuth 2.0
Demystifying OAuth 2.0
Karl McGuinness
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Authenticating Angular Apps with JWT
Authenticating Angular Apps with JWTAuthenticating Angular Apps with JWT
Authenticating Angular Apps with JWT
Jennifer Estrada
 

What's hot (20)

Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
JSON Web Tokens
JSON Web TokensJSON Web Tokens
JSON Web Tokens
 
Json Web Token - JWT
Json Web Token - JWTJson Web Token - JWT
Json Web Token - JWT
 
Angular Pipes Workshop
Angular Pipes WorkshopAngular Pipes Workshop
Angular Pipes Workshop
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Angular Advanced Routing
Angular Advanced RoutingAngular Advanced Routing
Angular Advanced Routing
 
Understanding JWT Exploitation
Understanding JWT ExploitationUnderstanding JWT Exploitation
Understanding JWT Exploitation
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
Callback Function
Callback FunctionCallback Function
Callback Function
 
Angular and The Case for RxJS
Angular and The Case for RxJSAngular and The Case for RxJS
Angular and The Case for RxJS
 
Cross-domain requests with CORS
Cross-domain requests with CORSCross-domain requests with CORS
Cross-domain requests with CORS
 
Json web token
Json web tokenJson web token
Json web token
 
Demystifying OAuth 2.0
Demystifying OAuth 2.0Demystifying OAuth 2.0
Demystifying OAuth 2.0
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Dom
DomDom
Dom
 
Authenticating Angular Apps with JWT
Authenticating Angular Apps with JWTAuthenticating Angular Apps with JWT
Authenticating Angular Apps with JWT
 

Similar to Creating custom Validators on Reactive Forms using Angular 6

mean stack
mean stackmean stack
mean stack
michaelaaron25322
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
Yakov Fain
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
angular-concepts-introduction-slides.pptx
angular-concepts-introduction-slides.pptxangular-concepts-introduction-slides.pptx
angular-concepts-introduction-slides.pptx
shekharmpatil1309
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Digamber Singh
 
Angular IO
Angular IOAngular IO
Angular IO
Jennifer Estrada
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
Commit University
 
Meetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son applicationMeetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son application
Thibault Even
 
01 startoff angularjs
01 startoff angularjs01 startoff angularjs
01 startoff angularjs
Erhwen Kuo
 
Full Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication SystemFull Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication System
Digamber Singh
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
Dev_Events
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
Bipin
 
Angular 2 in-1
Angular 2 in-1 Angular 2 in-1
Angular 2 in-1
GlobalLogic Ukraine
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
David Giard
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Frost
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
Ran Wahle
 
Unit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptxUnit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptx
Malla Reddy University
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
Ran Wahle
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
Katy Slemon
 

Similar to Creating custom Validators on Reactive Forms using Angular 6 (20)

mean stack
mean stackmean stack
mean stack
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
 
angular-concepts-introduction-slides.pptx
angular-concepts-introduction-slides.pptxangular-concepts-introduction-slides.pptx
angular-concepts-introduction-slides.pptx
 
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive FormsAngular 7 Firebase5 CRUD Operations with Reactive Forms
Angular 7 Firebase5 CRUD Operations with Reactive Forms
 
Angular IO
Angular IOAngular IO
Angular IO
 
Angular 2 - The Next Framework
Angular 2 - The Next FrameworkAngular 2 - The Next Framework
Angular 2 - The Next Framework
 
Meetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son applicationMeetup SkillValue - Angular 6 : Bien démarrer son application
Meetup SkillValue - Angular 6 : Bien démarrer son application
 
01 startoff angularjs
01 startoff angularjs01 startoff angularjs
01 startoff angularjs
 
Full Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication SystemFull Angular 7 Firebase Authentication System
Full Angular 7 Firebase Authentication System
 
Adding User Management to Node.js
Adding User Management to Node.jsAdding User Management to Node.js
Adding User Management to Node.js
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Front end development with Angular JS
Front end development with Angular JSFront end development with Angular JS
Front end development with Angular JS
 
Angular 2 in-1
Angular 2 in-1 Angular 2 in-1
Angular 2 in-1
 
Building a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web ServicesBuilding a TV show with Angular, Bootstrap, and Web Services
Building a TV show with Angular, Bootstrap, and Web Services
 
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
Building an angular application -1 ( API: Golang, Database: Postgres) v1.0
 
angularJs Workshop
angularJs WorkshopangularJs Workshop
angularJs Workshop
 
Unit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptxUnit 2 - Data Binding.pptx
Unit 2 - Data Binding.pptx
 
Angular js 2
Angular js 2Angular js 2
Angular js 2
 
Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...Understanding router state in angular 7 passing data through angular router s...
Understanding router state in angular 7 passing data through angular router s...
 

More from AIMDek Technologies

Unveiling Salesforce EinsteinGPT
Unveiling Salesforce EinsteinGPTUnveiling Salesforce EinsteinGPT
Unveiling Salesforce EinsteinGPT
AIMDek Technologies
 
Medical-Devices
Medical-DevicesMedical-Devices
Medical-Devices
AIMDek Technologies
 
Patient Centric Innovations
Patient Centric InnovationsPatient Centric Innovations
Patient Centric Innovations
AIMDek Technologies
 
Einstein Bots
 Einstein Bots Einstein Bots
Einstein Bots
AIMDek Technologies
 
What is RabbitMQ ?
What is RabbitMQ ?What is RabbitMQ ?
What is RabbitMQ ?
AIMDek Technologies
 
Introduction to Einstein Bots
Introduction to Einstein BotsIntroduction to Einstein Bots
Introduction to Einstein Bots
AIMDek Technologies
 
Design REST APIs using RAML
Design REST APIs using RAMLDesign REST APIs using RAML
Design REST APIs using RAML
AIMDek Technologies
 
Gamification in UX
Gamification in UXGamification in UX
Gamification in UX
AIMDek Technologies
 
Testing with cucumber testing framework
Testing with cucumber testing frameworkTesting with cucumber testing framework
Testing with cucumber testing framework
AIMDek Technologies
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
AIMDek Technologies
 
AWS Summit : Digital Transformation and Innovation with Cloud
AWS Summit : Digital Transformation and Innovation with CloudAWS Summit : Digital Transformation and Innovation with Cloud
AWS Summit : Digital Transformation and Innovation with Cloud
AIMDek Technologies
 
Concepts of business intelligence
Concepts of business intelligenceConcepts of business intelligence
Concepts of business intelligence
AIMDek Technologies
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
AIMDek Technologies
 
Microsoft: Multi-tenant SaaS with Azure
Microsoft: Multi-tenant SaaS with AzureMicrosoft: Multi-tenant SaaS with Azure
Microsoft: Multi-tenant SaaS with Azure
AIMDek Technologies
 
What is Serverless Computing?
What is Serverless Computing?What is Serverless Computing?
What is Serverless Computing?
AIMDek Technologies
 
Introduction to Artificial Intelligence and Machine Learning with Python
Introduction to Artificial Intelligence and Machine Learning with Python Introduction to Artificial Intelligence and Machine Learning with Python
Introduction to Artificial Intelligence and Machine Learning with Python
AIMDek Technologies
 
Leveraging smart technologies to transform the new challenging healthcare ind...
Leveraging smart technologies to transform the new challenging healthcare ind...Leveraging smart technologies to transform the new challenging healthcare ind...
Leveraging smart technologies to transform the new challenging healthcare ind...
AIMDek Technologies
 
Enabling intelligence for cr ms _ salesforce einstein
 Enabling intelligence for cr ms _ salesforce einstein Enabling intelligence for cr ms _ salesforce einstein
Enabling intelligence for cr ms _ salesforce einstein
AIMDek Technologies
 
Liferay for Healthcare IT Solutions
Liferay for Healthcare IT Solutions  Liferay for Healthcare IT Solutions
Liferay for Healthcare IT Solutions
AIMDek Technologies
 
Best practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on SalesforceBest practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on Salesforce
AIMDek Technologies
 

More from AIMDek Technologies (20)

Unveiling Salesforce EinsteinGPT
Unveiling Salesforce EinsteinGPTUnveiling Salesforce EinsteinGPT
Unveiling Salesforce EinsteinGPT
 
Medical-Devices
Medical-DevicesMedical-Devices
Medical-Devices
 
Patient Centric Innovations
Patient Centric InnovationsPatient Centric Innovations
Patient Centric Innovations
 
Einstein Bots
 Einstein Bots Einstein Bots
Einstein Bots
 
What is RabbitMQ ?
What is RabbitMQ ?What is RabbitMQ ?
What is RabbitMQ ?
 
Introduction to Einstein Bots
Introduction to Einstein BotsIntroduction to Einstein Bots
Introduction to Einstein Bots
 
Design REST APIs using RAML
Design REST APIs using RAMLDesign REST APIs using RAML
Design REST APIs using RAML
 
Gamification in UX
Gamification in UXGamification in UX
Gamification in UX
 
Testing with cucumber testing framework
Testing with cucumber testing frameworkTesting with cucumber testing framework
Testing with cucumber testing framework
 
Introduction to Blockchain
Introduction to BlockchainIntroduction to Blockchain
Introduction to Blockchain
 
AWS Summit : Digital Transformation and Innovation with Cloud
AWS Summit : Digital Transformation and Innovation with CloudAWS Summit : Digital Transformation and Innovation with Cloud
AWS Summit : Digital Transformation and Innovation with Cloud
 
Concepts of business intelligence
Concepts of business intelligenceConcepts of business intelligence
Concepts of business intelligence
 
Introduction to Apache Kafka
Introduction to Apache KafkaIntroduction to Apache Kafka
Introduction to Apache Kafka
 
Microsoft: Multi-tenant SaaS with Azure
Microsoft: Multi-tenant SaaS with AzureMicrosoft: Multi-tenant SaaS with Azure
Microsoft: Multi-tenant SaaS with Azure
 
What is Serverless Computing?
What is Serverless Computing?What is Serverless Computing?
What is Serverless Computing?
 
Introduction to Artificial Intelligence and Machine Learning with Python
Introduction to Artificial Intelligence and Machine Learning with Python Introduction to Artificial Intelligence and Machine Learning with Python
Introduction to Artificial Intelligence and Machine Learning with Python
 
Leveraging smart technologies to transform the new challenging healthcare ind...
Leveraging smart technologies to transform the new challenging healthcare ind...Leveraging smart technologies to transform the new challenging healthcare ind...
Leveraging smart technologies to transform the new challenging healthcare ind...
 
Enabling intelligence for cr ms _ salesforce einstein
 Enabling intelligence for cr ms _ salesforce einstein Enabling intelligence for cr ms _ salesforce einstein
Enabling intelligence for cr ms _ salesforce einstein
 
Liferay for Healthcare IT Solutions
Liferay for Healthcare IT Solutions  Liferay for Healthcare IT Solutions
Liferay for Healthcare IT Solutions
 
Best practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on SalesforceBest practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on Salesforce
 

Recently uploaded

Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Hivelance Technology
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
ayushiqss
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 

Recently uploaded (20)

Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
Multiple Your Crypto Portfolio with the Innovative Features of Advanced Crypt...
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdfWhy React Native as a Strategic Advantage for Startup Innovation.pdf
Why React Native as a Strategic Advantage for Startup Innovation.pdf
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 

Creating custom Validators on Reactive Forms using Angular 6

  • 1. 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
  • 2. 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
  • 3. Step 1: Create a project and add material library Ng new ng6material Cd ng6mateial Ng add @angular/material Ng serve www.aimdek.com
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. Step 3: contd. This will 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: 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
  • 10. 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
  • 11. 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
  • 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. 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
  • 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