Angular 2 Form validations and custom validation, How to Implement

In this tutorial, let’s implement the following angular 2 inbuilt validations and create a custom validation using angular 2 validate interface

  1. Required - The form field is mandatroy
  2. Maxlength - Maximum number of characters in the field.
  3. Minlength - Minimum number of characters in the field.
  4. Pattern - Regular expression to match the input values and validate.
  5. Custom Validator - Writing custom validation function to match password and confirm password fields.

Getting Started

Lets create a form component. I used angular CLI to generate the folder structure and created a form folder for component files. To style we are using bootstrap. The folder structure should look like this :

www.cuppalabs.com

Create Form Component

Following code creates a form component with the input fields. In the next steps, let see how we can apply validations on each of these fields. View Live Demo

  1. import { Component,Directive, forwardRef,
  2. Attribute,OnChanges, SimpleChanges,Input } from '@angular/core';
  3. import { NG_VALIDATORS,Validator,
  4. Validators,AbstractControl,ValidatorFn } from '@angular/forms';
  5. import { User } from './user';
  6. @Component({
  7. moduleId: module.id,
  8. selector: 'login-form',
  9. templateUrl: './login-form.component.html',
  10. styleUrls: ['./login-form.component.css']
  11. })
  12. export class LoginFormComponent {
  13. powers = ['Really Smart', 'Super Flexible',
  14. 'Super Hot', 'Weather Changer'];
  15. model = new User('','',null,'','','');
  16. submitted = false;
  17. onSubmit() { this.submitted = true; }
  18. newHero() {
  19. // this.model = new User('','');
  20. }
  21. }
  1. <div class="col-md-6">
  2. <h3>Angular 2 Form Validations Demo</h3>
  3. <form (ngSubmit)="onSubmit()" #loginForm="ngForm">
  4. <div class="form-group">
  5. <label for="name">Name</label>
  6. <input type="text" class="form-control" id="name" #name="ngModel">
  7. </div>
  8. <div class="form-group">
  9. <label for="name">Email Address</label>
  10. <input type="text" class="form-control" id="emailaddress" #email="ngModel">
  11. </div>
  12. <div class="form-group">
  13. <label for="name">Mobile Number</label>
  14. <input type="text" class="form-control" id="mobilenumber" #mobile="ngModel">
  15. </div>
  16. <div class="form-group">
  17. <label for="name">Password</label>
  18. <input type="password" class="form-control" id="password" #password="ngModel">
  19. </div>
  20. <div class="form-group">
  21. <label for="name">Confirm Password</label>
  22. <input type="password" class="form-control" id="confirmPassword" #confirmPassword="ngModel">
  23. </div>
  24. <button type="submit" class="btn btn-success btn-block" [disabled]="!loginForm.form.valid">Submit</button>
  25. </form>
  26. </div>
  1. import { Directive, forwardRef, Attribute } from '@angular/core';
  2. import { NG_VALIDATORS,Validator,
  3. Validators,AbstractControl,ValidatorFn } from '@angular/forms';
  4.  
  5. @Directive({
  6. selector: '[validateEqual][formControlName],[validateEqual][formControl],
  7. [validateEqual][ngModel]',
  8. providers: [
  9. { provide: NG_VALIDATORS,
  10. useExisting: forwardRef(() => EqualValidator),
  11. multi: true }
  12. ]
  13. })
  14. export class EqualValidator implements Validator {
  15. constructor( @Attribute('validateEqual') public validateEqual: string) {}
  16.  
  17. validate(c: AbstractControl): { [key: string]: any } {
  18. // self value (e.g. retype password)
  19. let v = c.value;
  20.  
  21. // control value (e.g. password)
  22. let e = c.root.get(this.validateEqual);
  23.  
  24. // value not equal
  25. if (e && v !== e.value) return {
  26. validateEqual: false
  27. }
  28. return null;
  29. }
  30. }
  1. export class User{
  2. constructor(
  3. public name:string,
  4. public email: string,
  5. public mobile: number,
  6. public gender: string,
  7. public password: any,
  8. public confirmPassword: any
  9. ){}
  10. }

Once we have created the form, it looks like something below.

www.cuppalabs.com

Now it’s time for us to apply the validations on each field.

First Name Validation

Requirement - Required and only alphabets allowed in the name field.

  • required attribute on input tag ensures that the filed value is mandatory.
  • pattern="[a-zA-Z][a-zA-Z ]+" attribute take a regex to check for only characters in the field.
  • [a-zA-Z][a-zA-Z ]+ is the regular expression to check for only alphabets.
  • name.valid is a boolean value to check if the field has any error on the validation attributes.
  • name.hasError('required')" returns true if the value is not entered.
  • name.hasError('pattern')" return true if the entered value does not match with the regular expression.

Based on the type of error, whether on required or on pattern attributes, the error messages are shown and hidden.

  1. <div class="form-group">
  2. <label for="name">Name</label>
  3. <input type="text" class="form-control" id="name"
  4. required
  5. pattern="[a-zA-Z][a-zA-Z ]+"
  6. [(ngModel)]="model.name" name="name"
  7. #name="ngModel">
  8. <div [hidden]="name.valid || name.pristine"
  9. class="alert alert-danger">
  10. <div [hidden]="!name.hasError('required')">Name is required</div>
  11. <div [hidden]="!name.hasError('pattern')">Only alphabetsallowed</div>
  12. </div>
  13. </div>

Email Address Validation

Requirement - Validate the email format joe@gmail.com. Entered email should be having valid email with @, .co or.com.

  • required attribute on input tag ensures that the filed value is mandatory.
  • pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$" takes regular expression ^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$ to check for valid email.
  1. <div class="form-group">
  2. <label for="name">Email Address</label>
  3. <input type="text" class="form-control" id="emailaddress"
  4. required
  5. [(ngModel)]="model.email" name="email"
  6. pattern="^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$"
  7. #email="ngModel">
  8. <div [hidden]="email.valid || email.pristine"
  9. class="alert alert-danger">
  10. <div [hidden]="!email.hasError('required')">Email is required</div>
  11. <div [hidden]="!email.hasError('pattern')">Email format should be
  12. <small><b>joe@abc.com</b></small>
  13. </div>
  14. </div>

Mobile Number Validation

Requirement - Should be only numbers and should have 10 digits only.

  • required attribute on input tag ensures that the filed value is mandatory.
  • pattern="[0-9]*" take regular expression [0-9]* to allow only numbers.
  • minlength="10" minlength of the input value should be 10.
  • maxlength="10" max length of the input value should be 10. Based on the type of error in each of the attributes above, the error messages are shown.
  1. <div class="form-group">
  2. <label for="name">Mobile Number</label>
  3. <input type="text" class="form-control" id="mobilenumber"
  4. required
  5. [(ngModel)]="model.mobile" name="mobilenumber"
  6. pattern="[0-9]*"
  7. minlength="10"
  8. maxlength="10"
  9. #mobile="ngModel">
  10. <div [hidden]="mobile.valid || mobile.pristine"
  11. class="alert alert-danger">
  12. <div [hidden]="!mobile.hasError('minlength')">Mobile should be 10digit</div>
  13. <div [hidden]="!mobile.hasError('required')">Mobile is required</div>
  14. <div [hidden]="!mobile.hasError('pattern')">Mobile numberr should be only numbers</div>
  15. </div>
  16. </div>

Password Matching Validation

Angular 2 does not provide any inbuilt validator to match password. We need to write a custom directive to validate password match. Let’s write the directive using the validator interface.

  1. import { Directive, forwardRef, Attribute } from '@angular/core';
  2. import { NG_VALIDATORS,Validator,
  3. Validators,AbstractControl,ValidatorFn } from '@angular/forms';
  4.  
  5. @Directive({
  6. selector: '[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]',
  7. providers: [
  8. { provide: NG_VALIDATORS, useExisting: forwardRef(() => EqualValidator), multi: true }
  9. ]
  10. })
  11. export class EqualValidator implements Validator {
  12. constructor( @Attribute('validateEqual') public validateEqual: string) {}
  13.  
  14. validate(c: AbstractControl): { [key: string]: any } {
  15. // self value (e.g. retype password)
  16. let v = c.value;
  17.  
  18. // control value (e.g. password)
  19. let e = c.root.get(this.validateEqual);
  20.  
  21. // value not equal
  22. if (e && v !== e.value) return {
  23. validateEqual: false
  24. }
  25. return null;
  26. }
  27. }

The EqualValidator directive needs to be added to the html code as shown below.

  • validateEqual="password" in which password is the name of the field whose value is to be matched.
  1. <div class="form-group">
  2. <label for="name">Password</label>
  3. <input type="password" class="form-control" id="password"
  4. required
  5. [(ngModel)]="model.password" name="password"
  6. #password="ngModel">
  7. <div [hidden]="password.valid || password.pristine"
  8. class="alert alert-danger">
  9. Password is required
  10. </div>
  11. </div>
  12. <div class="form-group">
  13. <label for="name">Confirm Password</label>
  14. <input type="password" class="form-control" id="confirmPassword"
  15. required
  16. validateEqual="password"
  17. [(ngModel)]="model.confirmPassword" name="confirmPassword"
  18. #confirmPassword="ngModel">
  19. <div [hidden]="confirmPassword.valid || confirmPassword.pristine"
  20. class="alert alert-danger">
  21. Passwords did not match
  22. </div>
  23. </div>

That’s all folks !!