Angular 2+中Validators.maxLength表单验证不生效问题
Angular表单maxLength验证不生效的解决方法
你遇到的问题有两个核心原因:
1. TypeScript代码存在语法错误
你的cVVCode控件的验证器数组结尾写错了,多了一个右括号,导致Validators.maxLength(4)没有被正确注册到验证器列表中。
修正后的TS代码:
this.customPaymentForm = new FormGroup({ amount: new FormControl(0, [Validators.required, Validators.pattern(/^\d{1,4}(\.\d{1,2})?$/)]), cVVCode: new FormControl('', [Validators.required, Validators.maxLength(4)]), })
2. input类型为number导致maxLength验证失效
Angular的Validators.maxLength是基于字符串长度进行验证的,而type="number"的输入控件会将值转为数字类型,数字没有length属性,因此验证逻辑无法触发。
解决方案二选一:
方案A:将input类型改为text并限制输入为数字
修改HTML中的input标签,同时通过pattern属性限制仅允许输入数字:
<div class="input"> <label for="">Cryptogramme visuel <span class="req">*</span></label> <input type="text" class="form-control" formControlName="cVVCode" placeholder="XXXX" pattern="[0-9]*" /> <div class="text-error" *ngIf="customPaymentForm.get('cVVCode').errors && (customPaymentForm.get('cVVCode').touched || customPaymentForm.get('cVVCode').dirty)"> <div *ngIf="customPaymentForm.get('cVVCode').hasError('required')">Cryptogramme visuel est requis.</div> <div *ngIf="customPaymentForm.get('cVVCode').hasError('maxlength')">Cryptogramme visuel doit avoir au maximum 4 caractères.</div> </div> </div>
方案B:保留number类型,使用自定义验证器
如果需要保留type="number",可以自定义一个验证器来检查数字的位数:
// 自定义验证器函数 maxDigits(max: number): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { if (!control.value) return null; // 将数字转为字符串后检查长度 const valueLength = control.value.toString().length; return valueLength > max ? { maxDigits: { requiredLength: max, actualLength: valueLength } } : null; }; } // 初始化表单时使用自定义验证器 this.customPaymentForm = new FormGroup({ amount: new FormControl(0, [Validators.required, Validators.pattern(/^\d{1,4}(\.\d{1,2})?$/)]), cVVCode: new FormControl('', [Validators.required, this.maxDigits(4)]), })
对应的HTML错误提示修改为:
<div *ngIf="customPaymentForm.get('cVVCode').hasError('maxDigits')">Cryptogramme visuel doit avoir au maximum 4 caractères.</div>
内容的提问来源于stack exchange,提问作者Kamran Khan
相关产品推荐
相关产品推荐

