自定义验证器formArray控件

自定义验证器formArray控件

问题描述:

我有一个formGroup,该formGroup的控件是formArrays,

I have a formGroup, the controls of this formGroup are formArrays,

我的计划是遍历formGroup.formArrays的值,并检查是否有任何值设置为true,如果可以,则一切正常.

my plan is to loop over the value of the formGroup.formArrays and check to see if any of the values are set to true, if so everything is ok.

但是正在发生的事情是;总是无效的

But what is happening is; it's always invalid

 static validate (control: AbstractControl): { [key: string]: boolean } | null  {
    let isChecked = false;
    const tempArray = [];
      for ( let i = 0; i < control.value.length; i++ ) {
      const val = control.value[i];
      tempArray.push(val);
      }
   isChecked = tempArray.find( el => el === true );
   if ( isChecked ) {
    return null;
    }
    return  {
      'isNotChecked' : true
    };
  }

因为返回错误的方式.即,如果无效,则返回null.

Because you have the returns the wrong way around.. i.e. If it's invalid return null.

如果您在文档中关注英雄.有双重否定..

If you were following the Heroes in docs. there's double negatives..

** A hero's name can't match the given regular expression */
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
  return (control: AbstractControl): {[key: string]: any} | null => {
    const forbidden = nameRe.test(control.value);
    return forbidden ? {'forbiddenName': {value: control.value}} : null;
  };
}

禁止-因为它不能匹配正则表达式.

forbidden - because it can't match Regex.

(正则表达式测试将为匹配返回true)

(regex test would return true for a match)

这是我的例子之一:

export function min(min: Number): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      const input = control.value,
      isValid = input < min;
      if(isValid) 
          return { 'minValue': {min} }
      else 
          return null;
    };
}

让我知道这是否有帮助.

Let me know if this helps.