Angular 2 custom validator with parameters

后端 未结 3 1144
悲&欢浪女
悲&欢浪女 2020-12-30 21:50

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 r

3条回答
  •  醉酒成梦
    2020-12-30 22:13

    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.

提交回复
热议问题