In this article well discuss Custom validation in angular
Custom Validations in Angular 4 can be performed either in Template Driven Forms / Model Driven Forms.
Types of validation in angular Agenda:
- Using Template driven Forms
- Using Model Driven Forms
Create the following files in src/app/

Using Template driven Forms
Step 1: Implement Validation Factory
- Validation Factory returns validation function, and to get access to the field value we need to pass the AbstractControl as a parameter to the validation function.
- When the validation is true return null, if our validation fails then return an object with the name custom validation directive which contains itself a property valid: false
Ex: Let assume out custom validation attribute is isLower, then if our validation fails then we need to return an object with the name of our custom validation directive with the valid property set to false.
let isValid = false;
if (isValid) {
return null;
} else {
return {
isLower: {
valid: false
}
};
File: app.CustomValidator.ts
import { AbstractControl, ValidatorFn} from '@angular/forms';
function validateUpperCaseFactory(): ValidatorFn {
return (c: AbstractControl) => {
let isValid = c.value.charAt(0).toUpperCase() === c.value.charAt(0);
if (isValid) {
return null;
} else {
return {
upper: {
valid: false
}
};
}
}
}
- Here I want to validate the username should get started with an uppercase character,
- Now I’ve created a ValidationFactory function with upper as object name, if it is valid our function returns a null value, else it returns upper object with property valid set to false.
Step 2: Create a reusable directive
Now our validation function is ready, now we need to make use of this validation as an attribute to form elements, to achieve that we need to create a Directive.
File: app.UpperCaseValidator.ts
import { Directive } from '@angular/core';
import { AbstractControl, ValidatorFn, Validator, NG_VALIDATORS, FormControl } from '@angular/forms';
function validateUpperCaseFactory(): ValidatorFn {
// your code for custom validation
}
@Directive({
selector: '[upper][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: UpperCaseValidator, multi: true }
]
})
export class UpperCaseValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = validateUpperCaseFactory();
}
validate(c: FormControl) {
return this.validator(c);
}
}
Step 3: Create a Component
File: app.component.ts
import {Component,ViewChild } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './template.html'
})
export class AppComponent {
@ViewChild("myForm") myform: any;
firstName: string;
submitForm(form: any) {
this.myform.reset();
}
}
Step 4: Create a template for our component
File: template.html
<form #myForm="ngForm" (ngSubmit)="submitForm(myForm.value)">
<div class="form-group">
<label>First Name</label>
<input type="text" name="firstName" [(ngModel)]="firstName" #first="ngModel" class="form-control" required pattern="[a-zA-Z0-9 ]+" upper/>
<div class="form-control-feedback" *ngIf="first.errors && (first.dirty || first.touched)">
<p *ngIf="first.errors.required">First Name is required</p>
<p *ngIf="first.errors.upper">First character must be of uppercase</p>
<p *ngIf="first.errors.pattern">First Name cannot contain special charaters (@, _, etc.,) </p>
</div>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
Step 5: Bootstrap the Component and declare Custom Directive
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { UpperCaseValidator} from './app.CustomValidator';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, UpperCaseValidator],
bootstrap: [AppComponent]
})
export class AppModule { }
Step 6: Create an HTML page in the src folder, refer main.js and add the component selector in the body tag.
File: src/TemplateDrivenForms.html
<!—After importing all required files from node modules -->
<script>
System.import('app/TemplateDrivenForms/main.js').catch(function (err) { console.error(err); });
</script>
<body>
<my-app>Loading...</my-app>
</body>
Output:

Using Model Driven Forms
From the above example, we want to perform the same validation using Model driven forms, whereas in model driven we can perform in two ways,
- FormGroup
- FormBuilder
Using FormGroup
Create the folder structure as follows in src/app/

Step 1: Create a component
File: app.component.ts
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './template.html'
})
export class AppComponent {
myForm: FormGroup;
emp: Emp = new Emp();
constructor() {
this.CreatingFormControls();
this.CreatingForm();
}
validateUpperCaseFactory(c: FormControl) {
let isValid = c.value.charAt(0).toUpperCase() === c.value.charAt(0);
if (isValid) {
return null;
} else {
return {
upper: {
valid: false
}
};
}
}
CreatingFormControls() {
this.emp.firstName = new FormControl('', [Validators.required, Validators.pattern("[a-zA-Z0-9 ]+"),this.validateUpperCaseFactory]);
}
CreatingForm() {
this.myForm = new FormGroup({
firstName: this.emp.firstName,
});
}
}
class Emp {
firstName: FormControl;
lastName: FormControl;
}
Step 2: Creating a template for the component
File: template.html
<form [formGroup]="myForm">
<div class="form-group">
<label>First Name</label>
<input type="text" name="firstName" class="form-control" formControlName="firstName" />
<div class="form-control-feedback" *ngIf="emp.firstName.errors && (emp.firstName.dirty || emp.firstName.touched)" style="color:red">
<p *ngIf="emp.firstName.errors.required">First Name is required</p>
<p *ngIf="emp.firstName.errors.upper">First character must be of uppercase</p>
<p *ngIf="emp.firstName.errors.pattern">First Name cannot contain special charaters (@, _, etc.,) </p>
</div>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
Step 3: Bootstrap the component from app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, ReactiveFormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
Output:

Using Form Builder
Using Form Builder: In this method instead of creating form instance using FormGroup, we will create it by using FormBuilder.
Step 1: Import FormBuilder and create a component, from the above example modify the component using form builder.
File: app.component.ts
import { Component, OnInit, Pipe } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: `./template.html`,
})
export class AppComponent {
validateUpperCaseFactory(c: FormControl) {
let isValid = c.value.charAt(0).toUpperCase() === c.value.charAt(0);
if (isValid) {
return null;
} else {
return {
upper: {
valid: false
}
};
}
}
myForm: FormGroup;
firstName: FormControl;
emp: Emp = new Emp();
constructor(private fb: FormBuilder) {
this.CreatingFormControls();
this.CreatingForm();
}
CreatingFormControls() {
this.emp.firstName = new FormControl('', [Validators.required, this.validateUpperCaseFactory]);
}
CreatingForm() {
this.myForm = this.fb.group({
firstName: this.emp.firstName
});
}
}
class Emp {
firstName: FormControl;
}
Now modify the template as follows
File: template.html
<form [formGroup]="myForm">
<div class="form-group">
<label>First Name</label>
<input type="text" class="form-control" formControlName="firstName" upper />
<div class="form-control-feedback" *ngIf="myForm.controls['firstName'].errors && (myForm.controls['firstName'].dirty || myForm.controls['firstName'].touched)" style="color:red">
<p *ngIf="myForm.controls['firstName'].errors.required">First Name is required</p>
<p *ngIf="myForm.controls['firstName'].errors.upper">First character must be of uppercase</p>
</div>
</div>
<div class="form-group">
<button type="submit">Submit</button>
</div>
</form>
Output:

thanks and you can see the following link for angular js and web API curd operation
- how to create ASP.NET Core 3 Web API Project - January 21, 2022
- JWT Authentication using OAUTH - January 10, 2022
- Ado.net database Transactions - January 9, 2022
tҺe website іѕ really good, I like it!
Bookmarked!, I like it!
First time visiting your website, I enjoy your web site!
tҺe website іѕ really good, I like your website!
First time visiting your website, I love your web site!
Saved as a favorite!, I love your website!