Click to See Complete Forum and Search --> : validating forms
hi this is really annoying me I know that I know it but I just can't quite get it working anyway,
I've got a text field in a form that needs to be filled with numbers so I want to verify that only numbers are used in that field
Exuro
06-27-2003, 12:40 AM
Here's one way to do it:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate() {
var valid=1
var numbers="0123456789"
for (i=0;i<=form1.input1.value.length-1;i++) {
if ( numbers.indexOf(form1.input1.value.charAt(i))<0 ) {
valid=0
}
}
if (valid==0) {
alert('Please enter only numbers')
}
else {
form1.submit()
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="form1">
<INPUT TYPE="text" NAME="input1" VALUE=""><BR>
<INPUT TYPE="button" VALUE="Submit" onClick="validate()">
</FORM>
</BODY>
</HTML>
This is more flexible construction
<script language="javascript">
function checkForm() {
var re = new RegExp('^[0-9]+$');
if (!re.test(form.name.value)) {
alert ('Error!');
return false;
}
return true;
}
</script>
<body>
<form name="form" onsubmit="if(!checkForm()) return false;">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
/^\d+$/.test(fieldvalue)
return true or false for number only
Charles
06-27-2003, 06:11 AM
Let's not forget negative numbers, decimals and scientific notation...
<input type="text" onchange="if (isNaN(this.value)) {alert('Please enter a Number.'); this.value = ''; this.focus()}">