Jump to content
xisto Community
TavoxPeru

Validate Numeric Only

Recommended Posts

Hi, this cool script created by: Manzi Olivier (http://www.imanzi.com/) verifies in real time that a input string is numeric, otherwise it deletes the non-numeric character. To configure it follow this steps:

Paste this code into an external JavaScript file named: validNum.js

// calculate the ASCII code of the given characterfunction 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="java script:checkNumber(myForm.txtNumber);"></form>

Of course, you need to add a submit or a button field and code its respective onclick or onsubmit event to really perform the submission of the data entered, but that is very easy to do, no?.

 

Best regards,

Share this post


Link to post
Share on other sites

Ahh...now this would be really useful for when collecting phone numbers and wishing to remove all the non numeric characters from it. I just read at AListApart that it would be friendlier to users if forms simply allowed users to fill in their phone number in whatever format they pleased. Thus, this script might prove useful. On a second note, it is Javascript, and I was thinking of sticking more to PHP, as Javascript could still be a usability problem for some of the security-freaked visitors. At least I know the server can always run my PHP scripts. :unsure:

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.