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

Community
  • 1
  • 1
Neil
  • 2,509
  • 7
  • 32
  • 47
  • 1
    do you think you are the first person trying to validate number with javascript in 2012? :) see [this](http://stackoverflow.com/q/1779013/944681) or [this](http://stackoverflow.com/q/18082/944681) – Michal Klouda Oct 06 '12 at 18:45
  • both those posts are validating numbers, i need a function that validates not empty and only numbers. – Neil Oct 06 '12 at 18:57

2 Answers2

1
function isNonEmptyNumber (str) {
  if(!str.length) return false;
  var num = +str;
  return isFinite(num) && !isNaN(num);
}
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
0

With regexp:

value.match(/^\d+$/)
Chocimier
  • 48
  • 2
  • 5