Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 444
adesh Avatar asked Jul 26 '26 10:07

adesh


1 Answers

// 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);
}
like image 169
Lukas Avatar answered Jul 28 '26 23:07

Lukas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!