angular 表单验证器验证的同时限制输入的实现(2)

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']), });

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a5f413a6f1eb53f82215f238ad3254cc.html