网络编程 发布日期:2025/11/9 浏览次数:1
几乎每个web应用都会用到表单,Angular 为我们提供了几个内置 validators (验证器),但在实际工作中为了满足项目需求,我们经常需要为应用添加一些自定义验证功能。
angular内置验证器
需求:设置成绩占比时,如果总占比不是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 "text-align: center">
明白了这个原理,就是根据需求进行改写:
// 判断总占比是否等于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 "color: #ff0000">添加到响应式表单
给要验证的 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">成绩总占比需等于100%!
</nz-form-explain>
</nz-form-control>
</nz-form-item>
效果:
总结
总的来说这个验证器实现起来不算很难,就是读懂官方文档,然后根据自己的需求进行改写。
参考文档:angular表单验证 跨字段验证
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。