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