【问题标题】:how to get the type of error of a Validator如何获取验证器的错误类型
【发布时间】:2021-08-26 14:10:22
【问题描述】:

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

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

【问题讨论】:

标签: angular forms validation customvalidator custom-errors


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    密码字段示例:

    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');
        }
      }
    }
    

    【讨论】:

    • 这两种情况都不起作用
    • 我测试了它的最小长度并且它有效,请记住错误名称必须相同。例如,我写了错误的“minLength”。它必须是“最小长度”。对于您的自定义“空间字符”自定义验证器,它必须是您返回的错误名称。
    • 更新了它以修复'minlength'...链接到工作示例:stackblitz.com/edit/angular-qh69zg?file=src/app/…
    【解决方案3】:

    目前我已经这样解决了:

     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'
             );
           }
         }
       }
    

    没事吧?

    【讨论】:

    • 是的,您可以这样做,即使对于更全面的表单错误,我建议您执行 Ramana 建议的操作,以便在每个相应的输入下显示错误,这样用户就可以将哪个错误与哪个输入关联起来.
    猜你喜欢
    • 2015-07-27
    • 2011-08-24
    • 2020-06-04
    • 2016-06-01
    • 2015-08-09
    • 2019-09-07
    • 2023-01-12
    • 2014-01-20
    • 1970-01-01
    相关资源
    最近更新 更多