34

How do I create let's say my own maxLength validator in Angular 2? All examples I could find use validators similar to 'required' one meaning that they already know the rules. They only accept one param - the control itself. How do I pass more parameters?

Here's the sample validator I have. How do I modify it to pass number 5 as a parameter?

export class MyValidators {
    static minValue(control:Control): {[s: string]: boolean} {
        var num = +control.value;
        if (isNaN(num) || num < 5 ) { return {"minValue": true}; }
        return null;
    }
}

3 Answers 3

47

Here is a sample. It's a min value validator where you pass in a number to validate.

import {Control} from 'angular2/common';

export const minValueValidator = (min:number) => {
  return (control:Control) => {
    var num = +control.value;
    if(isNaN(num) || num < min){
      return {
         minValue: {valid: false}
      };
    }
    return null;
  };
};

More details can be found in the Custom Validators official documentation page.

Sign up to request clarification or add additional context in comments.

5 Comments

minValueValidator = (min: number) => {} would be better ?!
That works. Thank you! I also added isNaN check and replaced 'export const' with 'static' to make it a member of a class.
Updated to include NAN check
how can i pass variable value to this validator ? i notice it always expects string constant like <elem minValueValidator="5"> and won't let me do <elem minValueValidator={{a}}>
This won't work with the AOT compiler since lambda isn't supported: angular.io/guide/aot-compiler
4

The minValueValidator example basically shows that you can use a factory for your custom validator so it will be something like this:

static minValue = (num: Number) => {
    return (control:Control) => {
         var num = control.value;
         if (isNaN(num) || num < 5 ) { return {"minValue": true}; }
         return null;
    }
}

In my case I use FormControl not Control

import { FormControl } from '@angular/forms';

Comments

3

Another solution here that uses a little more Angular nuance:

  static minValue(min: number): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      if (control.value == null || control.value == '') {
        //avoid validation if empty, we are not testing for required here
        return null;
      }
      const errors: ValidationErrors = {};
      let num = +control.value;
      if (isNaN(num) || num < min) {
        errors.isLessThanMin = {
          message: `Number must be greater that ${min}`
        };
      }
      return Object.keys(errors).length ? errors : null;
    };
  }

Now you have a much more reusable html error message

<div *ngIf="control.errors.isLessThanMin>{{control.errors.isLessThanMin.message}}</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.