JavaScript for float and integer number validation

26,655

Solution 1

// remove whitespaces
var input = input.replace(/\s+/g,"");

// check if the input is a valid number
if(isFinite(input) && input != ''){
  // do your thing
}

Remember that isFinite only accepts values like '20.50' and not '20,50' as is custom in some countries. If you need this kind of flexibility you need to do additional string preprocessing. And with this solution only spaces are allowed as thousand delimiters (e.g '100 000').

Unfortunately the check for an empty string is necessary since isFinite('') returns true.

You could also use this function from user CMS (for a detailed explanation see: Validate decimal numbers in JavaScript - IsNumeric())

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Solution 2

Best ever solution for me for numeric validation in javascript.

function isFloat(evt) {

var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
    alert('Please enter only no or float value');
    return false;
}
else {
    //if dot sign entered more than once then don't allow to enter dot sign again. 46 is the code for dot sign
    var parts = evt.srcElement.value.split('.');
    if (parts.length > 1 && charCode == 46)
      {
        return false;
      }


    return true;

}

}

Just Copy and past javascript code and apply to your textbox onkeypress like this ..

<input type="text" onkeypress="return isFloat(event)"  />

Solution 3

onload =function(){ 
  var ele = document.querySelectorAll('.number-only')[0];
  ele.onkeypress = function(e) {
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
        return false;
  }
  ele.onpaste = function(e){
     e.preventDefault();
  }
}
<input class="number-only" type=text />
Share:
26,655
adesh
Author by

adesh

Updated on February 28, 2020

Comments

  • adesh
    adesh over 4 years

    I tried to make a javascript function to validate integer values from a text box. What is the best way to validate it so that only integer and float values are acceptable?

    Required java script function for number validation.