- html监听验证
<nz-form-control>
<nz-form-label class="label" nzFor="integral">积分值</nz-form-label>
<input name="integral"
nz-input
placeholder=""
formControlName="point"
placeholder="请输入积分的值!"
type="number"
maxlength="8"
onkeyup="this.value=this.value.replace(/\D|^0/g,'')"
onafterpaste="this.value=this.value.replace(/\D|^0/g,'')"/>
<nz-form-explain *ngIf="mainForm.get('point')?.dirty && mainForm.get('point')?.hasError('required')">
请输入积分值!
</nz-form-explain>
<nz-form-explain *ngIf="mainForm.get('point')?.dirty && mainForm.get('point')?.hasError('numberErr')">
积分值介于1 ~ 99999999之间!
</nz-form-explain>
</nz-form-control>
- ts
ngOnInit() {
this.mainForm = this.fb.group({
point: [null, [Validators.required, this.numberValidator]],
radiovalue: [null, [Validators.required, ]]
});
}
// 自定义的验证方式
/**
* 验证器,输入的值在0-99999999之间
*/
private numberValidator = (control: FormControl): { [s: string]: boolean } => {
if (control.value && control.value < 0 || control.value > 99999999 ) {
return { numberErr: true, error: true };
} else {
return;
}
}
// 验证每个组件,如果有错误会显示信息
FormMethod.updateFormStatus(this.mainForm);
// 校验不通过,返回
if (!this.mainForm.valid) {
return;
}
// 动态添加表单控件
this.mainForm.addControl(`productNum${index}`, this.fb.control(null, [Validators.required, this.numberValidator]));
// 动态移除表单控件
this.mainForm.removeControl(`productName${this.orderProductList.length }`);
// 验证所有组件
// 表单部分的通用方法
export const FormMethod = {
/**
* 更新表单状态
* @param form FormGroup
*/
updateFormStatus: (form: FormGroup): void => {
for (const i of Object.keys(form.controls)) {
form.controls[i].markAsDirty();
form.controls[i].updateValueAndValidity();
}
}
};
- 常用验证规则
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。