Custom validation template driven angular 4

Updated : Oct 26, 2019 in Angular

Custom validation template driven angular 4

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 &amp;&amp; (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 &amp;&amp; (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
Custom validation template driven angular 4
Custom validation template driven angular 4

Leave a Reply

Your email address will not be published. Required fields are marked *