angular 实现同步验证器跨字段验证的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

angular 实现同步验证器跨字段验证的方法

陈杰   2020-05-16 我要评论

几乎每个web应用都会用到表单,Angular 为我们提供了几个内置 validators (验证器),但在实际工作中为了满足项目需求,我们经常需要为应用添加一些自定义验证功能。

angular内置验证器

  • required - 表单控件值非空
  • email - 表单控件值的格式是 email
  • minlength - 表单控件值的最小长度
  • maxlength - 表单控件值的最大长度
  • pattern - 表单控件的值需匹配 pattern 对应的模式(正则表达式)

需求:设置成绩占比时,如果总占比不是100%,则无法通过验证。

分析:需求很简单,只需要写一个验证器即可,由于不需要访问后台,且验证器与三个字段有关,所以是同步跨字段验证。

实现验证器

首先,去官网上找示例代码:

export const identityRevealedValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
 const name = control.get('name');
 const alterEgo = control.get('alterEgo');

 return name && alterEgo && name.value === alterEgo.value ? { 'identityRevealed': true } : null;
};

解释:这个身份验证器实现了 ValidatorFn 接口。它接收一个 Angular 表单控件对象作为参数,当表单有效时,它返回一个 null,否则返回 ValidationErrors 对象。

从上可知,所谓跨字段,就是从验证表单单个控件formControl变成了验证整个表单formGroup了,而formGroup的每个字段就是formControl。

明白了这个原理,就是根据需求进行改写:

  // 判断总占比是否等于100
  export const scoreWeightSumValidator: ValidatorFn = (formGroup: FormGroup): ValidationErrors | null => {
  const sumLegal = formGroup.get('finalScoreWeight')
    .value + formGroup.get('middleScoreWeight')
    .value + formGroup.get('usualScoreWeight')
    .value === 100;
    // 如果是,返回一个 null,否则返回 ValidationErrors 对象。
  return sumLegal ? null : {'scoreWeightSum': true};
};

到此,验证器已经写完。

添加到响应式表单

给要验证的 FormGroup 添加验证器,就要在创建时把一个新的验证器传给它的第二个参数。

  ngOnInit(): void {
  this.scoreSettingAddFrom = this.fb.group({
    finalScoreWeight: [null, [Validators.required, scoreWeightValidator]],
    fullScore: [null, [Validators.required]],
    middleScoreWeight: [null, [Validators.required, scoreWeightValidator]],
    name: [null, [Validators.required]],
    passScore: [null, [Validators.required]],
    priority: [null, [Validators.required]],
    usualScoreWeight: [null, [Validators.required, scoreWeightValidator]],
  }, {validators: scoreWeightSumValidator});
}

添加错误提示信息

我使用的是ng-zorro框架,当三个成绩占比均输入时,触发验证

  <nz-form-item nz-row>
  <nz-form-control nzValidateStatus="error" nzSpan="12" nzOffset="6">
    <nz-form-explain
      *ngIf="scoreSettingAddFrom.errors?.scoreWeightSum &&
       scoreSettingAddFrom.get('middleScoreWeight').dirty &&
       scoreSettingAddFrom.get('finalScoreWeight').dirty &&
       scoreSettingAddFrom.get('usualScoreWeight').dirty">成绩总占比需等于100%!
    </nz-form-explain>
  </nz-form-control>
</nz-form-item>

效果:

总结

总的来说这个验证器实现起来不算很难,就是读懂官方文档,然后根据自己的需求进行改写。

参考文档:angular表单验证 跨字段验证

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们