Web
Analytics
custom validators in angular 4 | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Custom Validators in Angular 5

Validators in angular 5, can we apply using two approaches first one is through HTML5 predefined  validations (like required, pattern etc. ) the second one is by using angular form-control class or model-driven approach but angular 5 provides another way through which we can create our own custom validators which may have different functionality which does not exist into predefined validations. In custom validators, we write some functions that will return validation output values (validate the value). These functions take value as abstract control as input and return an object as output. After creation of a custom validator, we can pass the reference of it into various components where we want to apply it.

So in this tutorial, I am going to describe that how we can apply custom validator in angular application

Step 1: Create a new customvalidator.ts file in the src folder and add following code into that.

import { AbstractControl } from '@angular/forms';
export class CustomValidators {
    static passwordStrength (control: AbstractControl) {
    if (CustomValidators.isEmptyValue(control.value)) {
    return null;
    }
    if (!control.value.match(/^(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9!@#\$%\^&\*]{8,}$/))
     {
    return {'weakPassword': true};
    }
    return null;
}
static isEmptyValue (value) {
return value == null ||
typeof value === 'string' && value.length === 0;
}
}

Step2. Create New Component(testcustomvalidator) and add following code to that

import { CustomValidators } from './../customvalidator';
import { Component, OnInit } from '@angular/core';
import { FormGroup, Validators, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-testcustomvalidator',
  templateUrl: './testcustomvalidator.component.html',
  styleUrls: ['./testcustomvalidator.component.css']
})
export class TestcustomvalidatorComponent implements OnInit {

  registrationForm: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.registrationForm = this.formBuilder.group({
      password: ['', [Validators.required,
      CustomValidators.passwordStrength]]
     });
  }
  onSubmit(formvalue)
  {
    console.log(formvalue);
    console.log(this.registrationForm.value);
  }

}

Testcustomvalidator.html

<p>
  testcustomvalidator works!
</p>
<form novalidate [formGroup]="registrationForm"  (ngSubmit)="onSubmit(registrationForm.value)">  
<input type="password" class="form-control"
 formControlName="password" >
<div class="error-message"
 *ngIf="registrationForm.get('password').touched &&
 registrationForm.get('password').hasError('required')">
The password is required.
</div>
<div class="error-message"
 *ngIf="registrationForm.get('password').touched &&
 registrationForm.get('password').hasError('weakPassword')">
The password must be minimum 8 characters, must contain at
least 1 lowercase alphabet, 1 uppercase alphabet, 1 numeric
character, 1 special character.
</div>
<button type="submit" class="btn btn-secondary" [disabled]="registrationForm.invalid">Submit</button>

</form>

Step 3: Pass reference of newly created component reference as a template in app.component.html

<app-testcustomvalidator></app-testcustomvalidator>

Step 4: Run Program:

ng serve –open

Output

Custom Validator Output

Custom Validator Output