Angular 2 自定义验证器,用于检查何时需要两个字段之一 [英] Angular 2 custom validator to check when either one of the two fields is required

查看:24
本文介绍了Angular 2 自定义验证器,用于检查何时需要两个字段之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个自定义验证器功能来检查是否输入了电话号码(家庭电话和手机).当它们都被触摸并且没有有效值时,我想在两个字段上显示错误消息,由于某种原因,我的代码没有按预期工作.请帮我处理这件作品.-谢谢!这是 stackblitz 链接 https://stackblitz.com/edit/angular-ve5ctu

I am trying to implement a custom validator function to check either of the Phone numbers(Home Phone and Mobile) are entered or not. I want to show the error message on both the fields when they are both touched and not have the valid value, for some reason my code is not working as anticipated. Please help me with this piece. -Thanks! Here is the stackblitz link https://stackblitz.com/edit/angular-ve5ctu

createFormGroup() {
   this.myForm = this.fb.group({
     mobile : new FormControl('', [this.atLeastOnePhoneRequired]),
     homePhone : new FormControl('', [this.atLeastOnePhoneRequired])
   });
}

atLeastOnePhoneRequired(control : AbstractControl) : {[s:string ]: boolean} {
  const group = control.parent;
  if (group) {
    if(group.controls['mobile'].value || group.controls['homePhone'].value) {
      return;
    }
  }
  let errorObj = {'error': false};
  return errorObj;
}

推荐答案

不要在每个 formControl 上标记验证器,而是为电话号码创建一个嵌套组并将验证器应用于该组.在本示例中,我将只在整个表单上应用验证器.

Instead of marking the validator on each formControl, make a nested group for the phone numbers and apply the validator to that group. In this sample I'll just apply the validator on the whole form.

此外,在应用验证器时,我们需要在字段有效时返回 null.

Also when applying validators we need to return null when the field is valid.

另外,由于您使用的是 Angular 材质,我们需要添加一个 ErrorStateMatcher 能够显示 mat-errors.mat-errors 仅在验证器设置为表单控件时显示,而不是表单组.

Also, since you are using Angular material, we need to add a ErrorStateMatcher to be able to show mat-errors. mat-errors show only when validators are set to form control, not a formgroup.

您的代码应如下所示:

createFormGroup() {
  this.myForm = this.fb.group({
    mobile : new FormControl(''),
    homePhone : new FormControl('')
      // our custom validator
  }, { validator: this.atLeastOnePhoneRequired});
}

atLeastOnePhoneRequired(group : FormGroup) : {[s:string ]: boolean} {
  if (group) {
    if(group.controls['mobile'].value || group.controls['homePhone'].value) {
      return null;
    }
  }
  return {'error': true};
}

错误状态匹配器:

export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const controlTouched = !!(control && (control.dirty || control.touched));
    const controlInvalid = !!(control && control.invalid);
    const parentInvalid = !!(control && control.parent && control.parent.invalid && (control.parent.dirty || control.parent.touched));

    return (controlTouched && (controlInvalid || parentInvalid));
  }
}

您在组件中标记的内容:

which you mark in component with:

matcher = new MyErrorStateMatcher();

然后在两个输入字段上将其标记到您的模板中.还要注意 *ngIf 如何寻找显示验证消息:

and then mark it to your template on both input fields. Also note how the *ngIf looks for displaying validation messages:

<mat-form-field>
  <input matInput placeholder="Mobile" formControlName="mobile" [errorStateMatcher]="matcher">
  <mat-error *ngIf="myForm.hasError('error')">
    "Enter either phone number"
  </mat-error>
</mat-form-field>
<mat-form-field>
  <input matInput placeholder="Home Phone" formControlName="homePhone" [errorStateMatcher]="matcher">
  <mat-error *ngIf="myForm.hasError('error')">
    "Enter either phone number"
  </mat-error>
</mat-form-field>

StackBlitz

这篇关于Angular 2 自定义验证器,用于检查何时需要两个字段之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆