4

Possible Duplicate:
Validate numbers in JavaScript - IsNumeric()

Hi I am trying to validate a field using javascript to ensure that the field is not empty AND only contains numbers

I am using document.getElementById to get the value of the field, then using this function to validate it:

function isNumeric(elem, message, messsage2)
{
   if(isNaN(elem))
   { 
    alert(message2); 
    return false; 
   }
   else if (elem == null || elem =="")
   {
    alert(message);
    return false;
   }
return true;
}

However this function still allows me to enter letters as where there should be numbers

2
  • 1
    do you think you are the first person trying to validate number with javascript in 2012? :) see this or this Commented Oct 6, 2012 at 18:45
  • both those posts are validating numbers, i need a function that validates not empty and only numbers. Commented Oct 6, 2012 at 18:57

2 Answers 2

1
function isNonEmptyNumber (str) {
  if(!str.length) return false;
  var num = +str;
  return isFinite(num) && !isNaN(num);
}
Sign up to request clarification or add additional context in comments.

Comments

0

With regexp:

value.match(/^\d+$/)

2 Comments

This will fail to match numbers like 1.2, -1, etc.
Yes, but then you'd get false positives like +++++ or .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.