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

问题描述

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

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

解决方法

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

您可以使用 "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');
    }
  }
}
,

暂时我是这样解决的:

SELECT client.name,client.balance,SUM(payment.amount) AS paid
FROM client,payment
WHERE payment.clientid = client.client_id
GROUP BY client.name,client.balance

可以吗?