Click to See Complete Forum and Search --> : form input field that only accepts numbers and decimal points


rory
01-31-2003, 05:23 AM
form input type that only accepts nu,mbers and decimal points if anyone got some code id really appreciate it

Charles
01-31-2003, 06:03 AM
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Form Example</title>
<form action="foo.pl">
<p>
<label for="number">Number:</label>
<br>
<input id="number" type="text" onchange="if (/[^\d\.]/.test(this.number.value) {alert('This field requires a Number'); this.value=''; this.focus()}">
</p>
<p>
<input type="submit">
</p>
</form>

But like all JavaScript, this will fail for a great number of users. In this case about 12% of them.

And if you want something that tests more specifically for a number (id est only one decimal point, negative numbers permitted) then this might do the trick:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="Content-Script-Type" content="text/javascript">
<title>Form Example</title>
<form action="foo.pl">
<p>
<label for="number">Number:</label>
<br>
<input id="number" type="text" onchange="if (/^\.?$/.test(this.value) || !/^-?\d*\.?\d*$/.test(this.value)) {alert('This field requires a Number'); this.value=''; this.focus()}">
</p>
<p>
<input type="submit">
</p>
</form>