Posted By

juzerali on 01/28/09


Tagged

javascript HATS


Versions (?)

To check whether a field is numeric by using JavaScript


 / Published in: JavaScript
 

This snippet contains a text input field called 'abc' and we calling the checkNum function as the onclick action of a button 'btn'

  1. function checkNum(){
  2.  
  3. var inputBox = document.getElementById('abc');
  4. if(inputBox.value.length!='0'){
  5. var j=0;
  6. var run = false;
  7. for(j=0; j<inputBox.value.length; j++){
  8. var char=inputBox.value.charAt(j);
  9.  
  10. if(inputBox.value.charAt(j)>='0' && inputBox.value.charAt(j)<='9'){
  11. run = true;
  12. }
  13. else{
  14. run = false;
  15. alert("Q# can only be a numeric value");
  16. document.getElementById('abc').focus();
  17. document.getElementById('abc').value="";
  18. break;
  19. }
  20. }
  21. if(run){
  22.  
  23. alert("The field has been successfully validated!");
  24. }
  25.  
  26.  
  27. }
  28. else if(inputBox.value.length == '0'){
  29. alert("Please enter a Q#");
  30. document.getElementById('abc').focus();
  31. }
  32. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: MMDeveloper on January 29, 2009

you could also just run a regexp test

var onlyNums = /[^0-9]/g;

if (onlyNums.test("asdf90")) { alert("numbers only"); }

Posted By: juzerali on April 13, 2009

thanks MMDeveloper.

Yours is a much better way to do it.

Cheers :)

Posted By: MMDeveloper on April 20, 2009

looking at this again, my input would be an integer validation, if you wanted to allow a floating point number as well, you could do something like [code] textBoxValue = "asdf 903.31"; floated = parseFloat(textBoxValue);

if (textBoxValue != floated) { alert("enter a number"); } else {} [/code] that will parseFloat the value (convert it to a floating point number) which should automatically strip out other characters. If you compare the parseFloat'd value with the original value and they match, then the original input was a number, if the 2 values do not match, then some non-numbers (or multiple decimals) were input.

You need to login to post a comment.