自定义验证器不会更改我的ngClass

时间:2019-07-12 20:59:24

标签: angular forms

我的console.log完全按照我的要求工作,但是在所有情况下都会显示错误。我可以看到这导致我的ngclass仅显示错误模式。

我的表单:

this.registerForm = this.formBuilder.group({
 pseudo: ['', [Validators.required, Validators.minLength(4)]],
 birthDate: ['', [Validators.required, majorValidator()]],
 email: ['', [Validators.required]],
 password: ['', [Validators.required, Validators.minLength(8)]],
});

我的自定义验证器:

export function majorValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    if (control.value !== '') {
      const diff = (Date.now().valueOf() - control.value) / (1000 * 60 * 60 * 24) / 365;
      if (diff > 18) {
        console.log('ok');
        return {'ageValid': {value: control.value}};
      } else {
        return null;
      }
    }
    return null;
  };
}

这是我的看法:

<div class="birthDate-response row mx-auto">
   <span class="mx-auto no-valid " *ngIf="f.birthDate.ageValid""> Vous devez avoir 18 ans au minimum </span>
</div>

如果您能找到解决方案,那么谢谢!!

1 个答案:

答案 0 :(得分:1)

您应该仔细看看有角度的文档。您对验证功能的理解不是100%正确:

It takes an Angular control object as an argument and returns either null if the form is valid, or ValidationErrors otherwise.

因此,基本上,在值有效的情况下,您忘记返回null

您需要至少18岁?也许然后您需要逆转条件:

if (control.value !== '') {
      const diff = (Date.now().valueOf() - control.value) / (1000 * 60 * 60 * 24) / 365;
      if (diff > 18) {
        console.log('ok');
        return null;
      } else {
        return {'ageValid': {value: control.value}};
      }
    }
    return null;

另外,这有点奇怪:Date.now().valueOf()-您的用户将以tick为单位输入年龄吗? :)

相关问题