Javascript can be used for form validation, to ensure that user entered the correct information.
Check whether user forget to enter information before submit the form:
<script language="javascript">
function checkform()
{
var val = document.fv.n.value;
if (val == "") {
alert("Error, nothing entered!");
return false;
}
return true;
}
</script>
<form name="fv" action="formvalidation.php"
onsubmit="return checkform()" method="post">
<center>Form Validation Test</center><br>
<TABLE width="100%"><TBODY><tr>
<td width=100 style="font-size:17px" align=right>
Input Text:</TD>
<td width=4></TD>
<td width=200><input name=n
style="width:200px;font-size:22px"></TD>
<td width=120>
<input name=submit value="Submit" type=submit
style="height:28px;width:120">
</td>
</tr></tbody></table><br>
</form>
Javascript can also be used to check the information entered by user dynamically.
Following example check whether user entered a number or not, if not, delete the
last input:
<script language="javascript">
function isNum(args)
{
args = args.toString();
if (args.length == 0)
return false;
for (var i = 0; i<args.length; i++){
if ((args.substring(i,i+1) < "0"
|| args.substring(i, i+1) > "9")){
return false;
}
}
return true;
}
function ivcheck(i)
{
var n = document.iv.n.value;
if (i == "1" && !isNum(n))
{
n = n.substring(0,n.length-1);
document.iv.n.value = n;
return;
}
}
</script>
<form name="iv">
<center>Input Box Validation Test</center><br>
<TABLE width="100%"><TBODY><tr>
<td width=120 style="font-size:17px" align=right>
Input Number:</TD>
<td width=4></TD>
<td width=200><input name=n
style="width:200px;font-size:22px"></TD>
<td width=100>
</td>
</tr></tbody></table><br>
</form>