Home » Featured, Headline, Software Development

Angular 4 – Writing custom validators for reactive forms

25 July 2017 No Comment

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!

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

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