<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>
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();
}
}
};