表单验证的两种方法:
一、onsubmit验证:
<script language="javascript"> function CheckPost () { if (addForm.user.value == "") { alert("请填写用户名!"); addForm.username.focus(); return false; } if (addForm.title.value.length < 5) { alert("标题不能少于5个字符!"); addForm.title.focus(); return false; } return true; } </script> <form action="test.php" method="post" name="addForm" onsubmit="return CheckPost();"> <p>用户:<input type="text" size="10" name="user" maxlength="20"/></p> <p>标题:<input type="text" name="title" maxlength="50"/></p> <p>内容:<textarea name="content" rows="8" cols="30"></textarea></p> <p><input type="submit" name="submit" onclick="SendForm();" value="发表留言"/></p> </form> <?php if($_POST[‘submit‘]) { echo "<script language=\"javascript\">alert(‘提交成功!‘);history.go(-1);</script>"; } ?>
二、onclick验证:
<script language="javascript"> function SendForm () { if(CheckPost()) { document.addForm.submit(); } } function CheckPost () { if (addForm.user.value == "") { alert("请填写用户名!"); addForm.username.focus(); return false; } if (addForm.title.value.length < 5) { alert("标题不能少于5个字符!"); addForm.title.focus(); return false; } return true; } </script>
时间: 2024-10-16 06:58:12