PDA

View Full Version : Validating--Making field accept numbers only



colbyco
Jun 1st, 2007, 04:15 AM
hello! I'm glad I found this site.
here is my problem; I hope someone can help me.

In my class, we are working on Client Side Validation, and one of the fields on my forms needs to be a number. So my question is, how do I make it so if a user types in a letter, an alert box pops up and says "You must enter a number."?

this is what I came up with, and of course, it doesn't work:

var validChars = "0123456789";
for (i = 0; i <11; i++)
{
brkString = times.charAt(i);
if (validChars.indexOf(brkString) == -1)
{
alert("You must enter an Integer");
return false;
}
}

by the way, the name of the form is "timesForm", and the id is "times".
any help would be really appreciated. Thank you.

colby

glenngv
Jun 1st, 2007, 06:14 AM
You don't have to loop through each character to check if the input is numeric or not. You can do it with isNaN (http://www.devguru.com/Technologies/ecmascript/quickref/isnan.html) method.

Philip M
Jun 1st, 2007, 07:42 AM
Try this:-

<form name = "timesForm">
<p> <input type = "text" name = "times" id = "times" onkeyup = "testForNum(this)" ></p>

<script type = "text/javascript">
function testForNum(which) {
if (isNaN(which.value)) {
alert ("You must enter an integer");
return false;
}
}
</script>

</form>