如何在Angular 2上实现我的自定义验证器?

时间:2016-06-28 21:26:46

标签: angular angular2-forms

如何在Angular 2中实现自定义验证器?

我找到this plunker

constructor(private fb: FormBuilder) {
    this.form = fb.group({
        'singleSelection': ['Rio', [App.validateCity]] // initial value as string
        'multipleSelection': [['Red','Blue'], [App.validateColor]]  // initial value as array
    });
}

static validateCity(c: FormControl) {
    if (c.value !== 'New York') {
        return { citySucks: true };
    }
    return null;
}

static validateColor(c: FormControl) {
    if (c.value.indexOf('Green') < 0) {
        return {badColor: true};
    }
    return null;
}

但是,我认为最好实现一个接口Validator,比如类MinLengthValidator。但是,我不知道如何使用它!

1 个答案:

答案 0 :(得分:1)

//控制处理

          this.form = fb.group({
            'singleSelection': ['Rio', this.text({min: 10})]
          });

//处理最小值的文本函数

           public static text(config = {}): ValidatorFn {
             return (control: Control): {} => {
                if(!control) {
                   return null;
                }

              let c: string = control.value;

            if(config.min) {
              if(c.length < config.min) {
                  return {
                  "This field must have at least " + config.min + " characters."
                  };
               }
             }
           }}