0

I'm looking to make a new function that will validate the field but allow for negative numbers aswell as positive e.g. =/- 999.99 . Would anyone have a quick and easy solution. Thanks

function validateNumber(thenumber){
    try{
        validnumbers = "0123456789.,";
    valid = false;
    for(i=0;i<thenumber.length;i++){
       if (validnumbers.indexOf(thenumber.charAt(i)) == -1)
       {
          valid = false;
          break;
       }
       else
          valid = true;
    }
    return valid;
    }catch(e){}
   }
topcat3
  • 2,561
  • 6
  • 33
  • 57

5 Answers5

7

What about this simple function?

function validateNumber(thenumber)
{
    thenumber = thenumber.replace(".", "").replace(",", ".");

    return !isNaN(thenumber);
}

Fiddle

The function removes dots then replaces comma with dots. Then it uses isNaN with negation to return if its valid or not. You may want to add a check if thenumber is a string to prevent runtime errors.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
2

Use isNaN

function validateNumber(thenumber){
    return !isNaN(thenumber);
   }

isNaN will return false for both positive and negative numbers

AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

I think the better way to do this is using regular expresions: The search() method uses an expression to search for a match, and returns the position of the match(return -1 in other case).Here is an example:

public function validNumber(number)
{
    return number.search("^[+-]?[0-9]{1,9}(?:\.[0-9]{1,2})?$") > 0;
}
Oscar Acevedo
  • 1,144
  • 1
  • 12
  • 19
0

try this:

function isNumber(value) {
  value = value.replace(',', '.');
  return !isNaN(value);
}

function isNegative(value) {
  return (isNumber(value) && value<0);
}

function isPositive(value) {
  return (isNumber(value) && value>0);
}

and as bonus (:

function isNumberWithDots(value) {
  value = value.split(',').join('').split('.').join('');
  return !isNaN(value);
}
num8er
  • 18,604
  • 3
  • 43
  • 57
0

Try this expression:

(number < 0)

It will be evaluated by JavaScript by first attempting to convert the left hand side to a number value.

Further details can be found here:

Javascript negative number

Conversely, this expression:

(number > 0)

will be evaluated by JavaScript in the same manner.

Community
  • 1
  • 1
Daniel Burgner
  • 224
  • 2
  • 6
  • 16