内容简介:需求:设置成绩占比时,如果总占比不是100%,则无法通过验证。分析:需求很简单,只需要写一个验证器即可,由于不需要访问后台,且验证器与三个字段有关,所以是同步跨字段验证。
需求:设置成绩占比时,如果总占比不是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表单验证 跨字段验证
以上所述就是小编给大家介绍的《angular 实现同步验证器跨字段验证》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Impractical Python Projects
Lee Vaughan / No Starch Press / 2018-11 / USD 29.95
Impractical Python Projects picks up where the complete beginner books leave off, expanding on existing concepts and introducing new tools that you’ll use every day. And to keep things interesting, ea......一起来看看 《Impractical Python Projects》 这本书的介绍吧!