需求:设置成绩占比时,如果总占比不是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表单验证 跨字段验证