adnan ali
adnan ali

Reputation: 43

How to display error message on max length exceed on angular input?

I want to limit input name to 45 and show message on limit exceed. here below I am attaching my html file and ts file . I using angular 10 . Also is there any other way to apply limit on input and display warning message . Thanks

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>

Upvotes: 1

Views: 3357

Answers (2)

Mr. Stash
Mr. Stash

Reputation: 3140

  • When you add multiple validators you need to pass them as an array of validators.
  • Remove maxlength="45" from the input element if you want to trigger the error state, otherwise input will only accept a maximum of 45 characters and the input will always be valid.
'username': new FormControl('', [Validators.required, Validators.maxLength(45)]),

Upvotes: 1

Tanner
Tanner

Reputation: 2411

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

The error property name is maxlength, not maxLength. Just update your template and it should work.

Upvotes: 0

Related Questions