Introduction

In your HTML page add the control you want to validate but for this sample, I used textbox to demonstrate this code, in my textbox control I used onkeyup event to validate whether recently entered character is numeric or not. so you can call this JavaScript code as your requirement in your project.
Test.html
  1. <input type="text" id="txt" name="txt" onkeyup="txtValidate(this.id)"/>
JavaScript Code
  1. function txtValidate(txtid)
  2. {
  3. var ok = 0;
  4. var a = document.getElementById(txtid).value;
  5. for (var i = 0; i <= a.length - 1; i++)
  6. {
  7. var j = a.charCodeAt(i);
  8. for (var k = 48; k <= 57; k++)
  9. {
  10. ok = 0;
  11. if (k == j)
  12. {
  13. ok = 1;
  14. break;
  15. }
  16. }
  17. }
  18. if (ok == 0)
  19. {
  20. alert("Only Numeric Values Allowed");
  21. document.getElementById(txtid).value = "";
  22. for (var i = 0; i < a.length - 1; i++)
  23. {
  24. var j = a.charCodeAt(i);
  25. for (var k = 48; k <= 57; k++)
  26. {
  27. ok = 0;
  28. if (k == j)
  29. {
  30. document.getElementById(txtid).value += a.charAt(i);
  31. }
  32. }
  33. }
  34. }
  35. }
I hope this code helps you. Thank you.