Angular响应式表单MinLength校验未显示错误问题求助
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>
2. Optional: Add Number-Only Validation (Recommended)
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

