In this article, we will learn about custom validation template driven angular 4
the previous template driven form validation we have used HTML5 built-in validators, now let us create our own custom validators which can be added to input elements as a directive.
CustomValidator: That takes input with first character uppercase
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.
Create a new file
File: app.UpperCaseValidator.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
}
};
}
}
}
Step2: 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.
import { AbstractControl, ValidatorFn} from '@angular/forms';
function validateUpperCaseFactory(): ValidatorFn {
....
}
@Directive({
selector: '[upper][ngModel]',
providers: [
{ provide: NG_VALIDATORS, useExisting: UpperCaseValidator, multi: true }
]
})
export class UpperCaseValidator implements Validator {
validator: ValidatorFn;
constructor() {
this.validator = validateUpperCaseFactory();
}
// When using Model driven forms use the below validate function
//Option: 1
validate(c: FormControl) {
return this.validator(c);
}
//When using Template driven forms use the below validate function
//Option: 2
validate(c: AbstractControl) {
return this.validator(c);
}
}
Step3: Import custom validator in the component
File: app.component.ts
import { Component, OnInit, Pipe } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { UpperCaseValidator } from './app.CustomValidators';
@Component({
selector: 'my-app',
templateUrl: `./template.html`,
})
export class FormComponent implements OnInit {
constructor(private fb: FormBuilder) { }
myform: FormGroup;
changes:string[] = [];
ngOnInit() {
this.myform = this.fb.group({
myname: ['', UpperCaseValidator]
});
}
Step4: Implement the custom validator to the form element
// for Model-driven forms use the below template
Option: 1
File: template.html
<form [formGroup]="myform" (ngSubmit)="onSubmit(myform.value)" novalidate>
<div class="form-group">
<label>Enter Name</label>
<input type="text" class="form-control" formControlName="myname" upper />
<div class="form-control-feedback" *ngIf="myform.controls['myname'].errors && (myform.controls['myname'].dirty || myform.controls['myname'].touched)">
<p *ngIf="myform.controls['myname'].errors.required">Name is required</p>
<p *ngIf="myform.controls['myname'].errors.upper">Name should start with an uppercase</p>
</div>
</div>
<pre>{{myform.value | json}}</pre>
</form>
//If you are using Template-driven forms use the below template
Option: 2
<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>
<pre>{{myform.value | json}}</pre>
</form>
OutPut: Custom validation template driven angular

- 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
Saved as a favorite!, I like your web site!
Bookmarked!, I like it!
First time visiting your website, I like your blog!
tҺe website іѕ really good, I like your web site!