Home > Back-end >  Input type="number" is working fine on Chrome but allowing the characters other than numbe
Input type="number" is working fine on Chrome but allowing the characters other than numbe

Time:10-04

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!

CodePudding user response:

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;
        }
    }
  • Related