如何获取验证器的错误类型

how to get the type of error of a Validator

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

  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
     } 
   }

您可以使用 "hasError()" 来为每个错误指定您想要 return 的消息。

密码字段示例:

onSubmit(): void {
  if (this.formGroup.invalid) {
    if (this.formGroup.get('password').hasError('minlength')) {
      console.log('number of characters less than 8 ');
    }
    if (this.formGroup.get('password').hasError('SpecialCharacters')) {
      console.log('you have not entered any special characters');
    }
  }
}

另一个选项是访问 formGroup 控件错误,例如密码字段:

onSubmit(): void {
  if (this.formGroup.invalid) {
    if (!!this.formGroup.controls.password.errors?.minlength) { // force it to return false if error not found
      console.log('number of characters less than 8 ');
    }
    if (!!this.formGroup.controls.password.errors?.SpecialCharacters)) {
      console.log('you have not entered any special characters');
    }
  }
}

我会为特定的 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>

目前我是这样解决的:

 onSubmit(): void {
     if (this.formGroup.valid) {
       alert('Password salvata correttamente');
       this.formGroup.reset();
     } else {
       if (this.formGroup.controls.password.errors.minlength) {
         alert('ERROR MINLENGTH');
       }
       if (this.formGroup.controls.password.errors.specialCharacters) {
         alert(
           'ERROR SPECIALCHARACTERS'
         );
       }
     }
   }

还好吗?