• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Forms / Validate Numeric Only

Validate Numeric Only

This script verifies that a string is numeric, otherwise it deletes the non-numeric character.

<!– Paste this code into an external JavaScript file named: validNum.js  –>

/* This script and many more are available free online at
The JavaScript Source :: http://javascriptsource.com
Created by: Manzi Olivier :: http://www.imanzi.com/ */

// calculate the ASCII code of the given character
function CalcKeyCode(aChar) {
  var character = aChar.substring(0,1);
  var code = aChar.charCodeAt(0);
  return code;
}

function checkNumber(val) {
  var strPass = val.value;
  var strLength = strPass.length;
  var lchar = val.value.charAt((strLength) – 1);
  var cCode = CalcKeyCode(lchar);

  /* Check if the keyed in character is a number
     do you want alphabetic UPPERCASE only ?
     or lower case only just check their respective
     codes and replace the 48 and 57 */

  if (cCode < 48 || cCode > 57 ) {
    var myNumber = val.value.substring(0, (strLength) – 1);
    val.value = myNumber;
  }
  return false;
}
<!– Paste this code into the HEAD section of your HTML document.
     You may need to change the path of the file.  –>

<script type=”text/javascript” src=”validNum.js”></script>
<!– Paste this code into the BODY section of your HTML document  –>

<form name=”myForm” method=”post” action=”#”>
  Enter an integer here: <input name=”txtNumber” type=”text”
    id=”txtNumber” onKeyUp=”javascript:checkNumber(myForm.txtNumber);”>
</form>

Forms

Related Snippets:

  • Automatically expand a textarea as the user types
  • Trigger an event
  • Serialize form data into a query string
  • Virtual Keyboard Interface

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers