View Full Version : Only Allow Digits and "/"

05-30-2006, 08: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!

05-30-2006, 08: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

05-30-2006, 09: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"
<html xmlns="http://www.w3.org/1999/xhtml">
<title>numbers and /'s only</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<style type="text/css">
fieldset {
border:0 solid;

<script type="text/javascript">
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.');


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