如何识别哪个自定义验证函数导致 Reactive Forms 中的错误

How to identify which custom validation function is causing error in Reactive Forms

我将多个验证器分配给一个 formControl,其中 formControlName 作为 firstName。 如何知道哪个验证出错,以便我可以给出适当的消息

以下是我为 required

定制的验证函数
export function required() {
  return function(control:FormControl)
  {
    var value: string = control.value;
    value = value.trim();
    if(value.length == 0)
      return {required:true};    
    return null;
  } 
 }

并且使用是这样的

<md-error [hidden]="!firstName.errors.required || (!firstName.touched && !submitted)">
   Name is required
</md-error>

我收到以下错误

ERROR TypeError: Cannot read property 'required' of null

如果您正在使用 模板驱动表单 您的输入标签中需要提到的方法。

  <input type="text" class="form-control" #nameRef="ngModel" ngModel required name="name" placeholder="Enter Name">

或者在响应式方法的情况下

this.userForm = this.fb.group({
      name:[[],[<any>Validators.required]],
   })

您的 errors 可能为空,因此您应该使用 elvis 或安全导航运算符:?. 如下所示:

<md-error [hidden]="!firstName.errors?.required || (!firstName.touched && !submitted)">
   Name is required
</md-error>

您在评论中提到:

i dont want to use libraby validators , i want to use custom validators, required is just an example

如果您不打算使用Reactive Forms approach mentioned in you will need to create a Directive as described in this blog post(下面粘贴相关代码)

import { AbstractControl, ValidatorFn } from '@angular/forms';

// validation function
function validateJuriNameFactory() : ValidatorFn {
  return (c: AbstractControl) => {

    let isValid = c.value === 'Juri';

    if(isValid) {
        return null;
    } else {
        return {
            juriName: {
                valid: false
            }
        };
  }
}

@Directive({
  selector: '[juriName][ngModel]'
})
export class JuriNameValidator implements Validator {
  validator: ValidatorFn;

  constructor() {
    this.validator = validateJuriNameFactory();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }
}

您可以向验证器返回的错误对象添加附加信息:

export function required(String info) {
  return function(control:FormControl)
  {
    var value: string = control.value;
    value = value.trim();
    if(value.length == 0)
      return {required:true, info: info};    
    return null;
  } 
 }
his.userForm = this.fb.group({
  name:[[],[<any>required('firstName')]],
})
<md-error [hidden]="!firstName.errors.required || (!firstName.touched && !submitted)">
   <div *ngFor="let err of firstName.errors">
     {{error?.info}}
   </div>
</md-error>
<md-error *ngIf="firstName.hasError('required') && (firstName.touched || submitted)">
   Please enter the required field
</md-error>

这对我有用。

firstName.errors.required 不起作用

感谢大家的帮助。

如果有多个验证失败和多条消息,那么您可以通过添加 css

来仅显示第一条错误消息
md-error:not(:first-of-type) { display: none; }