Madhav Varshney
Madhav Varshney

Reputation: 3

Input type="number" is working fine on Chrome but allowing the characters other than numbers in Firefox

I am working in Angular, I need to put an input that only accepts numeric characters. I have tried giving type="number", it is working very fine in Google Chrome, but in firefox, the input still accepting non-numeric characters. I have solved this by typescript/ Javascript but wondering if there is any more natural solution for it. Any help would be appreciated. Thanks in advance!

Upvotes: 0

Views: 932

Answers (1)

Onenesslover
Onenesslover

Reputation: 154

In HTML you have to use keypress method

<input type="text" (keypress)="keyPressNumbers($event)" formControlName="yourformcontrolname" class="form-control"  />

In typescript you have to use this method by

const keyDecimal : boolean = false; 
             
keyPressNumbers(event) {

var perValue = this.yourformgroupname.get('yourvariablename').value;

var charCode = (event.which) ? event.which : event.keyCode;

if ((perValue.toString().indexOf(".") == -1) || (Number.isInteger(perValue)) || (perValue == null)) {

       this.keyDecimal = false;

     }

if (charCode< 45 || charCode> 57) {
       event.preventDefault();
       return false;
    } 

else {
       if (charCode == 46 && !this.keyDecimal) {
        this.keyDecimal = true;
    }
else if ((charCode == 46 && this.keyDecimal) || (charCode == 47)) {
         event.preventDefault();
        return false;
    }
       return true;
    }
}

Upvotes: 1

Related Questions