Home > Software engineering >  How to display max limit error message without using ts file in angular?
How to display max limit error message without using ts file in angular?

Time:11-23

I want to show error message like required error message for max input limit but using below code it work for required but not for maxlength . I also not to use ts file . Is there any way to achieve this. Thanks

<form #featureForm="ngForm">
<mat-form-field  appearance="fill">
  <mat-label>Feature Namre</mat-label>
  <input matInput [(ngModel)]="featureName" required name="featureName" maxlength="64" (ngModelChange)="moduleNameChange($event)" />
  <mat-error *ngIf="featureForm.controls['featureName']?.errors?.required">Feature Name is required.</mat-error>
  <mat-error *ngIf="featureForm.controls['featureName']?.errors?.maxlength">Maximum limit exceed.</mat-error>
</mat-form-field>
</form>

CodePudding user response:

According to documentation for HTML attribute: maxlength, the browser will generally prevent the user from entering more text than the maxlength attribute allows. This explains why you don't see the error message when typing into the input.

However, if the value is longer than the maxlength on the .ts side of things, then the code you have will render the error text. For instance assuming maxlength=10 and if featureName = '12345678901' <- string is longer than maxlength so error message would render on the page.

See this stackblitz for an example.

CodePudding user response:

There are two approaches to this.

1. Use reactive forms approach

2. Use template forms approach

As per your requirement, you don't want to use the .ts file for validation. Then you can proceed with template-driven forms in angular rather than proceeding with the reactive forms-driven approach. Reactive Forms driven approach mainly deals with forms of validation-related logic in the .ts file itself. While in the template-driven approach it does handle the logics in the template itself.

For further reading on reactive-forms in angular

For further reading on template-forms in angular

Please refer to the code block below :

<form #featureForm="ngForm">
       <mat-form-field  appearance="fill">
         <input matInput name="featureName" [ngModel]="featureName"  maxlength="10" #featureName="ngModel" required>
            
        <div *ngIf="featureName.errors" [ngClass] = "'error'"> 
          <div *ngIf="featureName.errors.maxlength">
                 Name must be at least  10 characters long.
          </div>
          <div *ngIf="featureName.errors.required">
             featureName is required.
          </div>
        </div>
      </mat-form-field>
</form>
  • Related