以实例说明问题吧:
<html>
<head>
<title>javascript validate sample</title>
<script language="javascript" src="common.js"></script>
<!--
下面是一段javascript代码,定义一个函数inputCheck(),实现实现form表单用户名\密码的验证
-->
<script language="javascript">
<!--
function inputCheck()
{
var eleValue = document.form1.userName.value;
if(eleValue == "")
{
alert("please input your username!");
document.form1.userName.focus();
return false;
}
eleValue = document.form1.password.value;
if(eleValue == "")
{
alert("please input your password!");
document.form1.password.focus();
return false;
}
eleValue = document.form1.age.value;
if(!isNumber(eleValue))
{
alert("age requires number only!");
document.form1.age.focus();
return false;
}
eleValue = document.form1.introduction.value;
if(eleValue.length > 2)
{
alert("max length execeeded!");
document.form1.introduction.select();
return false;
}
return true;
}
-->
</script>
</head>
<body>
<!-- 是一个简单的form表单,通过调用javascript function实现验证 -->
<form name="form1" method="post" action="">
<table border="1" align="center">
<tr>
<td>UserName<font color="red">*</font></td>
<td><input type="text" name="userName" value="" maxlength="15" size="10"></td></td>
</tr>
<tr>
<td>Password<font color="red">*</font></</td>
<td><input type="password" name="password" value="" maxlength="15" size="10"></td>
</tr>
<tr>
<td colspan="4" align="center">
<input type="submit" value=" ok " onclick="return inputCheck()">
<input type="reset" value=" clear ">
</td>
</tr>
</table>
</form>
<body>