Preventing users from entering non-numeric characters

Hello,

I have the following code that i am using to try and prevent users from entering non-numeric characters but it doesn’t seem to work:


	function validate_onkeypress() {
		 a = String.fromCharCode(event.keyCode);
		 b = a.charCodeAt(0);
		 if (!validateString(b)) return false;
		 return true;
	}
	
	function validateString(ch){
	  var checkOK = "0123456789.";
	  var allValid = true;
	  for (var j = 0;  j < checkOK.length;  j++)
		 if (ch == checkOK.charAt(j)) break;
	  if (j == checkOK.length) allValid = false;
	  return allValid;
	}

And then this is my textbox:


<input type=text name="TicketCost" id="TicketCost" size=8 onkeypress="validate_onkeypress" />

But it does not seem to work. All i want to do is prevent the user from entering non numeric values…

Can anyone see what i’m doing wrong?

Thanks

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">

            function validateInp(elem) {
                var validChars = /[0-9]/;
                var strIn = elem.value;
                var strOut = '';
                for(var i=0; i < strIn.length; i++) {
                  strOut += (validChars.test(strIn.charAt(i)))? strIn.charAt(i) : '';
                }
                elem.value = strOut;
            }

        </script>
    </head>
    <body>

        <div>
            <input type="text" name="inp1" onkeyup="validateInp(this);" />
        </div>

    </body>
</html>

Here is a way to do it without neeeding to check each character. Just try to turn the string into a Number object. If it has any non numbers it will return a NaN. Try running the code to carry out a few examples.

[HIGHLIGHT=“”]
<!doctype HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=windows-1252”>
<title>Check for non-number input</title>
<script type=“text/javascript”>
<!–
function getNumber()
{ var testString=document.myForm.myNumber.value;
// try to turn the input into a Number object
var numbr=new Number(testString);
// test to see if your succeeded
if(isNaN(numbr))
{ alert(testString+" is not a number. Please enter a valid number"); }
else
{ alert(“valid number”);}
}
// ------
–>
</script>
</head>

<body>

<div>
<form name=“myForm”>
<p><input type=“text” name=“myNumber” value size=“20”>
<input type=“button” value=“Enter” name=“myButton” onclick=“getNumber()”>
</p>
</form>
</div>

</body>

</html>

Since the op used onkeypress in the input, I think he/she wants to check each character as it is entered in the text box to see if it is numeric or not and not after some other button is clicked.

btw - I think the “inner cogs and pulleys” of isNaN probably checks each character in the input individually to determine whether the input is a number or not, so you are still most probably checking each character (indirectly) but in your case you are checking the whole string after it is entered rather than after each character is entered.

Since the op used onkeypress in the input, I think he/she wants to check each character as it is entered in the text box to see if it is numeric or not and not after some other button is clicked.

My response was a proof of concept, not a piece of code ready to drop into a web page. The relevant point is that checking the string by trying to turn it into a number object gives you a way to separate numbers from non numbers. How this is used in the web page is up to the enquirer. The script shown above lets you try various inputs so that you can determine the script’s response.

no problem :slight_smile:

I didn’t say your code doesn’t work. The point I was making is that I think the op wants to check each char as it is entered and not after the whole string string has been entered. I’m also not sure your comment saying your code doesn’t check each character is entirely correct. I suspect isNaN checks each character internally in the fuction itself and so you are most probably indirectly checking each character where I was directly checking each character.

It’s no big deal :slight_smile: as the op can use whatever method he/she wants

Thank you for your responses. I was actually trying to check for each character not after the full string has been entered. I would have liked to prevent users from being able to click a non-numeric character but i was not quite sure how to do this.

But thanks to both of your replies i got it working, so now when a user enters a non-numeric character an alert box appears, so that’s perfect! :slight_smile:

Thanks again…