onlyNumberValidator(formKeys: string[]): ValidatorFn { return (formGroup: FormGroup): ValidationErrors | null => { for (const key of formKeys) { const value = formGroup.controls[key].value; if (value && !/^\d*$/.test(value)) { formGroup.controls[key].setValue(value.replace(/[^0-9]/ig, ''), { onlySelf: true, }); } } return null; }};
使用:
this.validateForm = this.fb.group({ typeList: [[]], feeRate: [null, [Validators.required, Validators.pattern(/^[0-9]+(.[0-9]{1,2})?$/), Validators.max(0.999)]], code: [33, [Validators.required, Validators.maxLength(6)]], }, { validator: this.onlyNumberValidator(['code']), });