Back to article

JavaScripts: Prevent a User from Entering Non-numeric Characters

January 31, 2002

This article was contributed by Bart T. McDonough.

Environment: IE 4.0 and above

Function Name: "CheckNumeric()"

This Javascript function prevents a user from being able to enter non-numeric data into a text field in an HTML form. When a user types data into a text field that uses this function, only numeric characters which are typed actually appear in the field. Any other characters are ignored and do not appear. It is a useful tool if you're looking for a simple way to ensure you have numeric data without having to write a validation routine.

To use this function, simply call it as an "onkeypress()" event handler in your <INPUT> tag in your HTML code. To see how this is done, view or download the source code below.

This function does not require any input parameters and does not output any return value.

function CheckNumeric()
   // Get ASCII value of key that user pressed
   var key = window.event.keyCode;

   // Was key that was pressed a numeric character (0-9)?
   if ( key > 47 && key < 58 )
      return; // if so, do nothing
      window.event.returnValue = null; // otherwise, 
	                               // discard character


Download demo project - .97 Kb
Download source - 1.11 Kb


Date Posted: January 31, 2002

# # #

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date