【问题标题】:Angular custom validator messageAngular 自定义验证器消息
【发布时间】:2021-03-17 09:04:35
【问题描述】:

我有一个自定义验证器来验证我的数据库中是否存在序列号。 当找不到序列号但我做不到时,我想在表单的字段中显示特定的错误消息。我尝试了不同的方法,但结果并不好。 当我尝试在我的模板中插入此代码时

<div *ngIf="deviceInfos.controls.serial.errors && serial != null">
              Error
            </div>

即使在用户输入字段之前,错误消息也会显示。 我是 Angular 的新手,我实际上迷失在这个问题中。

这是我的自定义验证器

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AbstractControl, AsyncValidator, FormControl } from '@angular/forms';
import { map, catchError } from 'rxjs/operators';
import { of } from 'rxjs';


@Injectable({
  providedIn: 'root',
})
export class HttpRequestValidation implements AsyncValidator {
  
  constructor(private http: HttpClient) {}

  validate = (control: AbstractControl) => {

    const { value } = control;
    console.log(value);
    
    return this.http.get<any>(`http://127.0.0.1/backend/api-vitoapp/verify-serial.php?serial=${value}`)
      .pipe(

        map(() => {
            
          return null;
        }),
        catchError((err) => {
 
          console.log(err);
          return of (err);
        })
      );
  };
}

这是我的组件的一部分

 deviceSelected : any;
  serial = new FormControl('');
  
  constructor(private fb: FormBuilder,
              private hardwareCheckService: HardwareCheckService) {
  }

  ngOnInit() {
    
    this.deviceInfos = this.fb.group({
      serial: [null, [Validators.required, this.httpRequestValidation.validate]],
      deviceType: [this. deviceTypeOptions[0]],
    });
  }

有人可以帮助我吗? 非常感谢。

【问题讨论】:

    标签: angular typescript angular-reactive-forms


    【解决方案1】:

    看看这个。这会有所帮助。

    import { FormControl } from '@angular/forms';
    
    export function validateJson(input: FormControl): object | null {
        try {
            if (input.value) {
                JSON.parse(input.value);
            }
    
            return null;
        } catch (error) {
            return { invalidFormat: {message: "your message here"} };
        }
    }
    

    如果存在错误,在 HTML 中显示如下消息

    <div *ngIf="formControl.errors.invalidFormat && formControl.dirty">
            {{ formControl.errors.invalidFormat.message}}
    </div>
    

    【讨论】:

    • 感谢您的回复和帮助。我试图将您的代码插入到我的验证中,就像这样 `return null; }), catchError((err) => { console.log(err); return of ({ invalidFormat: {message: 'your message here'} }); }) );` 并在我的模板中插入 ngIf像这样的错误消息&lt;div *ngIf="serial.errors.invalidFormat &amp;&amp; serial.dirty"&gt; {{ serial.errors.invalidFormat.message}} &lt;/div&gt; 但在我的控制台中我收到错误无法读取 null 的属性 invalidFormat。
    • 将您的代码更改为:&lt;div *ngIf="serial.errors.invalidFormat &amp;&amp; serial.dirty"&gt;{{ serial?.errors?.invalidFormat.message}} &lt;/div&gt; 这样它将检查空对象,并且在没有验证错误的情况下,您不会在控制台中看到该错误。
    【解决方案2】:

    最后我像这样修改了我的验证器

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { AbstractControl, AsyncValidator, FormControl } from '@angular/forms';
    import { map, catchError } from 'rxjs/operators';
    import { of } from 'rxjs';
    
    
    @Injectable({
      providedIn: 'root',
    })
    export class HttpRequestValidation implements AsyncValidator {
      
      constructor(private http: HttpClient) {}
    
      validate = (control: AbstractControl) => {
    
        const { value } = control;
        console.log(value);
        
        return this.http.get<any>(`http://127.0.0.1/backend/api-vitoapp/verify-serial.php?serial=${value}`)
          .pipe(
    
            map(() => {
                
              return null;
            }),
            catchError((err) => {
     
              console.log(err);
              return of ({ invalidFormat: {message: 'Device not found in database'} });
            })
          );
      };
    
    
    }
    

    并像这样修改了我的模板

    <div *ngIf="deviceInfos.controls.serial.hasError('invalidFormat')">
           <span class="alert">{{ deviceInfos.get('serial').errors.invalidFormat.message}}</span> 
    </div>
    

    我不知道这是否是最好的方法,但现在可以了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      • 2017-12-06
      • 1970-01-01
      相关资源
      最近更新 更多