Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 custom validator with parameters

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;     } } 
like image 208
rook Avatar asked Apr 20 '16 22:04

rook


1 Answers

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.

like image 99
TGH Avatar answered Oct 16 '22 04:10

TGH