adesh
adesh

Reputation: 852

JavaScript for float and integer number validation

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.

Upvotes: 3

Views: 28559

Answers (5)

Ravinder Singh Bhanwar
Ravinder Singh Bhanwar

Reputation: 824

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)"  />

Upvotes: 2

anjaly
anjaly

Reputation: 518

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 />

Upvotes: 1

Vijay
Vijay

Reputation: 8451

var valid = !isNaN(value); Eg:

!isNaN('0'); // true
!isNaN('34.56'); // true
!isNaN('.34'); // true
!isNaN('-34'); // true
!isNaN('foo'); // false
!isNaN('08'); // true

!isNaN(''), !isNaN(' '), !isNaN('\n\t'), etc are all true!

Whitespace test + isNaN FTW:

var valid = !/^\s*$/.test(value) && !isNaN(value);

Upvotes: 0

Lukas
Lukas

Reputation: 376

// 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);
}

Upvotes: 7

sgowd
sgowd

Reputation: 2262

JavaScript has a built in function, isNaN(text). Just pass the text of your text box to this function to get a Boolean result.

Upvotes: 0

Related Questions