1

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>

2 Answers 2

1
  • 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)]),
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.