Reputation: 2642
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
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
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
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:
Conversely, this expression:
(number > 0)
will be evaluated by JavaScript in the same manner.
Upvotes: 0
Reputation: 30607
Use isNaN
function validateNumber(thenumber){
return !isNaN(thenumber);
}
isNaN
will return false for both positive and negative numbers
Upvotes: 2
Reputation: 21475
What about this simple function?
function validateNumber(thenumber)
{
thenumber = thenumber.replace(".", "").replace(",", ".");
return !isNaN(thenumber);
}
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