首页 > 解决方案 > 如何获取验证器的错误类型

问题描述

我有一个简单的输入,我想在提交时获取错误类型。

  formGroup: FormGroup = this.fb.group({
     password: [
       '',
       [Validators.required, Validators.minLength(8), SpecialCharacters],
     ],
   });

例如:

   onSubmit(): void {
     if (this.formGroup.invalid) {
       //I get the type of error:
         //number of characters less than 8 
         //you have not entered any special characters
     } 
   }

标签: angularformsvalidationcustomvalidatorcustom-errors

解决方案


我会为特定的 formControl 尝试这样的事情

get getPassword(): AbstractControl {
  return this.formGroup.get('password');
}

从 .html

<div *ngIf="getPassword.errors?.minLength">Minimum Length **</div>
<div *ngIf="getPassword.errors?.maxLength">Max Length ***</div>

推荐阅读