【问题标题】:Angular 2 custom validator to check when either one of the two fields is requiredAngular 2自定义验证器检查何时需要两个字段之一
【发布时间】:2017-12-10 17:01:27
【问题描述】:

我正在尝试实现自定义验证器功能来检查是否输入了电话号码(家庭电话和手机)。我想在两个字段都被触摸并且没有有效值时显示错误消息,由于某种原因我的代码没有按预期工作。请帮我完成这件作品。 -谢谢! 这是stackblitz链接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;
}

【问题讨论】:

标签: angular angular-reactive-forms angular-validation


【解决方案1】:

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

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

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

您的代码应如下所示:

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

您在组件中使用的标记:

matcher = new MyErrorStateMatcher();

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

<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

【讨论】:

  • 如何使控件在这里无效?因为,如果我们在这个表单中有其他字段,当表单无效时它们都会变红(controlTouched && (controlInvalid || parentInvalid)) 例如:StackBlitz。 @AJT_82 非常感谢您的回复。
  • 不要在表单控件上设置errorStateMatcher。正如我在上面提到的,当在表单组上设置错误时需要它。有了表单控件,你就不需要它了 :)
  • 我的意思是我的评论:mat-errors show only when validators are set to form control, not a formgroup.
  • (controlTouched &amp;&amp; (controlInvalid || parentInvalid)) 在存在其他无效控件时使当前控件变为红色,即使当前控件有效。可能是我没有朝着正确的方向思考。不过感谢您的帮助。
  • 我不明白你的意思?如前所述,如果您从表单控件中删除错误状态匹配器,它不应该这样做吗? stackblitz.com/edit/angular-kcqyse-nuesey?file=app/…
猜你喜欢
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-28
  • 2018-07-28
  • 1970-01-01
相关资源
最近更新 更多