Angular 10输入框超出最大长度时如何显示错误提示?
一、先修正你当前代码的问题
你的现有代码有两处关键错误,导致长度限制提示无法正常触发:
- TS文件中验证器参数位置错误
FormControl的第二个参数是同步验证器数组,第三个是异步验证器。你把Validators.maxLength(45)放在了第三个参数位置,这会被当作异步验证器处理,完全起不到同步验证的作用。正确写法是把多个同步验证器塞进同一个数组里:
newUserRegForm = new FormGroup({ 'username': new FormControl('', [Validators.required, Validators.maxLength(45)]), // 修正:将验证器放入数组 'password': new FormControl('', Validators.required), 'cpassword': new FormControl('', Validators.required), 'role': new FormControl('Security Engineer', Validators.required), 'projectAccessId': new FormControl([]), 'userEmail': new FormControl('', Validators.email), });
- HTML中错误的验证器key
Angular的maxLength验证器对应的错误key是小写的maxlength,不是驼峰式的maxLength,所以你原来的hasError('maxLength')永远会返回false。修正后:
<mat-error *ngIf="newUserRegForm.get('username').touched && newUserRegForm.get('username').hasError('maxlength')"> 用户名长度不能超过<strong>45</strong>个字符 </mat-error>
另外你已经给input加了maxlength="45",这个原生属性会直接阻止用户输入超过45个字符,结合表单验证器可以在用户粘贴超长内容时(虽然原生属性也会截断,但验证器能确保表单状态正确)触发提示。
二、其他实现输入长度限制并提示的方法
1. 自定义验证器(适合灵活场景)
如果需要动态调整长度、或者添加自定义提示逻辑,可以自己写验证器:
在TS文件里定义验证器函数:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'; export function maxLengthValidator(maxLength: number): ValidatorFn { return (control: AbstractControl): ValidationErrors | null => { if (!control.value) return null; return control.value.length > maxLength ? { customMaxLength: { max: maxLength, actual: control.value.length } } : null; }; }
然后在FormControl里使用:
'username': new FormControl('', [Validators.required, maxLengthValidator(45)]),
HTML里的错误提示可以显示更详细的信息:
<mat-error *ngIf="newUserRegForm.get('username').touched && newUserRegForm.get('username').hasError('customMaxLength')"> 用户名最多允许{{ newUserRegForm.get('username').getError('customMaxLength').max }}个字符,当前输入了{{ newUserRegForm.get('username').getError('customMaxLength').actual }}个 </mat-error>
2. 延迟验证(减少实时验证的频繁触发)
如果希望用户输入完、失去焦点再触发验证,而不是每输入一个字符就校验,可以给FormControl加updateOn选项:
'username': new FormControl('', { validators: [Validators.required, Validators.maxLength(45)], updateOn: 'blur' // 仅在输入框失去焦点时验证 }),
3. 模板驱动表单(不使用响应式表单的场景)
如果你更习惯用模板驱动的方式,代码可以这么写:
HTML文件:
<form #newUserRegForm="ngForm"> <mat-form-field class="registerInputForm" fxFlex> <mat-label>User Name</mat-label> <input matInput maxlength="45" name="username" [(ngModel)]="username" required #usernameCtrl="ngModel"> <mat-error *ngIf="usernameCtrl.touched && usernameCtrl.hasError('required')"> Username is <strong>required</strong> </mat-error> <mat-error *ngIf="usernameCtrl.touched && usernameCtrl.hasError('maxlength')"> maximum length <strong>exceed</strong> </mat-error> </mat-form-field> </form>
TS文件里只需要定义绑定的变量:
username: string = '';
内容的提问来源于stack exchange,提问作者adnan ali
相关产品推荐
相关产品推荐

