1

I am using Angular-7 for my Web Portal project. In one of the fields, I used number input type. This allows the user to use vertical scrollbar to scroll between 1 to 20. Also, I validated the maxlength as 2.

client.component.ts

numberOnly(event): boolean {
 const charCode = (event.which) ? event.which : event.keyCode;
 if ((charCode > 31) && (charCode < 48 || charCode > 57)) {
   return false;
   }
 return true;
}

client.component.html

<div class="col-xs-6">
   <label for="truck_required">Required Truck(s)<span style="color:red;"> *</span></label>
   <input type="number" (keypress)="numberOnly($event)" class="form-control" id="truck_required" placeholder="1,2,3..." min="1" max="20" name="truck_required" [(ngModel)]="form.truck_required" #truck_required="ngModel" [ngClass]="{'is-invalid' : truck_required.invalid && ((truck_required.dirty || truck_required.touched) || clientquoteForm.submitted)}" required maxlength="2">
   <div class="form-feedback" *ngIf="truck_required.invalid && ((truck_required.dirty || truck_required.touched) || clientquoteForm.submitted)" class="invalid-feedback">
   <div style="color:red;" *ngIf="truck_required.errors?.required"class="alert alert-danger">Required Truck(s) is required.</div>
</div>

I expect that when the user wants to type, the maxlength should be 2, but the application allows the user to type to any length as shown below.

error

How do I resolve this?

1

1 Answer 1

1

You have provided max="20" . please change max="20" to max="2". don't need to provide maxlength="2" attribute there. So remove the maxlength="2" attribute for number field.

<input type="number" (keypress)="numberOnly($event)" class="form-control" id="truck_required" placeholder="1,2,3..." min="1" max="2" name="truck_required" [(ngModel)]="form.truck_required" #truck_required="ngModel" [ngClass]="{'is-invalid' : truck_required.invalid && ((truck_required.dirty || truck_required.touched) || clientquoteForm.submitted)}" required>

and update this method as

numberOnly(event): boolean {
 if(event.target.value.length > 2)
{return false;}
 const charCode = (event.which) ? event.which : event.keyCode;
 if ((charCode > 31) && (charCode < 48 || charCode > 57)) {
   return false;
   }
 return true;
}
Sign up to request clarification or add additional context in comments.

1 Comment

- I did as you advised, but the problem is still there

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.