...

View Full Version : Only Allow Digits and "/"



xxwhocaresxx
05-30-2006, 07:19 PM
I have a textbox on a form that is used for a date. I am trying to use javascript to prevent users from typing anything but numeric data or a "/". I have everything working but allowing the backslash. This is what my function looks like:



function allowDigits(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode

if (charCode == 8 || charCode == 37 || charCode == 39)
return true;

if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;

return true;
}


In the first if statement when I try and add charCode == 191 || charCode == 111 that doesn't work to allow the backslash. Any ideas? I am not sure what I am doing wrong.

Thanks in advance!

Beagle
05-30-2006, 07:37 PM
Why check on every keypress? Why not use a regular expression once they finished typing?

In other words, I don't know the answer to your question.

The simplest would be that slash is not 191 or 111

coothead
05-30-2006, 08:38 PM
Hi there xxwhocaresxx,

and a warm welcome to these forums. :)

Try it like this...


<!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>numbers and /'s only</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
/*<![CDATA[*/
fieldset {
border:0 solid;
}
/*//]]>*/
</style>

<script type="text/javascript">
//<![CDATA[
window.onload=function() {
document.forms[0][1].onkeyup=function() {
if(this.value.match(/([^\d\/])$/)) {
alert('Come on stop messing about.\nthis box is for numbers and"/\'s" only.\nWe do not want to see any "'+RegExp.$1+'\'s" here thank you.');
document.forms[0][1].value=this.value.replace(RegExp.$1,'');
}
}
}
//]]>
</script>

</head>
<body>

<form action="#">
<fieldset>
<input type="text"/>
</fieldset>
</form>

</body>
</html>

coothead



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum