You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular响应式表单MinLength校验未显示错误问题求助

Angular Reactive Forms: minLength Validation Not Working for Phone Number Input

Got it, let's sort out why your phone number's minimum length validation isn't triggering the error message. The root cause is a case mismatch in the validation error key—Angular uses all lowercase for built-in validator error keys, but you're checking for a camelCase version. Here's how to fix it step by step:

1. Fix the Error Key in Your Template

Angular's Validators.minLength() returns an error object with the key minlength (all lowercase), not minLength (camelCase). Your current template checks for errors?.minLength, which won't find the error even when the validation fails.

Update your label's condition to use minlength instead:

<label *ngIf="service.formModel.get('PhoneNo').touched && service.formModel.get('PhoneNo').errors?.minlength">
  Minimum 7 digits required
</label>

Since your input is a phone number, you probably want to restrict users to entering only digits. Add Validators.pattern(/^\d+$/) to your validators array to ensure non-numeric characters don't count toward the length:

// Service.ts (or wherever your FormGroup is defined)
PhoneNo: ['', [
  Validators.required,
  Validators.minLength(7),
  Validators.pattern(/^\d+$/) // Ensures only digits are entered
]]

3. Clean Up Your Template (Optional but Best Practice)

Repeating service.formModel.get('PhoneNo') throughout your template is messy and can cause unnecessary change detection cycles. Instead, create a getter in your component to reference the control directly:

// In your component class
get phoneNoControl() {
  return this.service.formModel.get('PhoneNo');
}

Then update your template to use this getter for cleaner code:

<input class="full-width has-padding has-border" 
       formControlName="PhoneNo" 
       type="tel" 
       placeholder="Mobile *" />

<img src="../../../../assets/img/required-img.png" 
     class="required-img" 
     *ngIf="phoneNoControl.touched && phoneNoControl.errors?.required" 
     title="This field is mandatory" 
     data-toggle="tooltip" />

<label *ngIf="phoneNoControl.touched && phoneNoControl.errors?.minlength">
  Minimum 7 digits required
</label>

Why This Works

Angular's built-in validators (like minLength, maxLength, required) all return error keys in all lowercase. So when the validation fails, the error object will have errors.minlength instead of errors.minLength—that's why your original condition never evaluated to true.

内容的提问来源于stack exchange,提问作者Zain Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:29:10