【问题标题】:How to display error message on max length exceed on angular input?如何在角度输入超出最大长度时显示错误消息?
【发布时间】:2022-11-22 01:18:38
【问题描述】:

我想将输入名称限制为 45 并在超过限制时显示消息。下面我附上了我的 html 文件和 ts 文件。我使用角度 10 。还有其他方法可以限制输入并显示警告消息。谢谢

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),
});
<form [formGroup]="newUserRegForm">
  <mat-form-field class="registerInputForm" fxFlex>
    <mat-label>User Name</mat-label>
    <input matInput maxlength="45" formControlName="username">
    <mat-error *ngIf="newUserRegForm.get('username').touched &&
                   newUserRegForm.get('username').hasError('required')">
      Username is <strong>required</strong>
    </mat-error>
    <mat-error *ngIf="newUserRegForm.get('username').touched && 
                   newUserRegForm.get('username').hasError('maxLength')">
      maximum length <strong>exceed</strong>
    </mat-error>
  </mat-form-field>
  <br>
  <mat-form-field *ngIf="!data?.user" class="registerInputForm">
    <mat-label>Password</mat-label>
    <input matInput type="password" formControlName="password">
    <mat-error *ngIf="newUserRegForm.get('password').touched && 
               newUserRegForm.get('password').hasError('required')">
      Password is <strong>required</strong>
    </mat-error>
  </mat-form-field>
</form>

【问题讨论】:

    标签: javascript angular forms validation angular-material


    【解决方案1】:

    https://angular.io/api/forms/Validators#maxlength

    错误属性名称是maxlength,而不是maxLength。只需更新您的模板,它就可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 2018-08-13
      • 1970-01-01
      相关资源
      最近更新 更多