Angular 4 – Writing custom validators for reactive forms

Angular 4 provides common validators that can be used for form field validation. But sometimes a need arises for custom validation on form fields as per business rule.

Creating a validator function
decimalPlacesEqualTo is a custom validator that has been created and used in form field validation.

// ... validators.ts
import { FormControl, ValidatorFn } from '@angular/forms';

export function decimalPlacesEqualTo(n: number): ValidatorFn {
    return (c: FormControl): {[key: string]: any} => {
      if (util.countDecimalPlaces(c.value) === n) {
        return null;
      } else {
         return { 'decimalPlacesEqualTo' : true };
      }
    };
  }

// util.countDecimalPlaces
export function countDecimalPlaces(value: any): number {
    if (_.isEmpty(value) || value.indexOf('.') < 0) {
      return 0;
    }
    if (Math.floor(value) === value) {
      return 0;
    }
    return value.toString().split('.')[1].length || 0;
}

Usage in components
This can then be used in Angular form components as below. The totalPurchase field will only validate if the value is float and has 2 decimal places otherwise the form field is invalid and will prompt error.

 import * as validator from './validators';

 this.customerForm= this.fb.group({
    totalPurchase: ['', [validator.decimalPlacesEqualTo(2]]
 });

Hope this helps the readers, post suitable for >= intermediate developers!

Add a Comment

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image