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

Time:11-22

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  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" >
    <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>

CodePudding user response:

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

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

CodePudding user response:

  • 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)]),
  • Related