topcat3
topcat3

Reputation: 2642

Validate Negative Number

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){}
   }

Upvotes: 0

Views: 5735

Answers (5)

Oscar Acevedo
Oscar Acevedo

Reputation: 1212

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

Upvotes: 1

num8er
num8er

Reputation: 19372

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

Upvotes: 0

Daniel Burgner
Daniel Burgner

Reputation: 224

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.

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30607

Use isNaN

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

isNaN will return false for both positive and negative numbers

Upvotes: 2

DontVoteMeDown
DontVoteMeDown

Reputation: 21475

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.

Upvotes: 7

Related Questions