表单验证的两种方式:
一、使用alert提示框
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""/TR/html4/loose.dtd"><html><head><title>JavaScript基础</title><script type="text/javascript">function check_form(){if(document.form1.title.value == ""){alert('标题不能为空!');document.form1.title.focus();return false;}if(document.form1.content.value == ""){alert('内容不能为空!');document.form1.content.focus();return false;}return true;}</script></head><body><form method="post" action="" name="form1" onsubmit="return check_form()">标题:<input type="text" name="title"><br><br>内容:<textarea rows="10" cols="30" name="content"></textarea><br><br><input type="submit" value="提 交"></form></body></html>
这种验证方式适合学习使用,但是真实项目中一般不建议用alert,用户体验不好。
二、标签方式
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""/TR/html4/loose.dtd"><html><head><title>JavaScript基础</title><script type="text/javascript">function check_form(tmp_form){var err = document.getElementById('error_tips');if(tmp_form.title.value == ""){err.innerHTML = "标题不能为空!";err.style.color = "red";err.style.fontSize = "9px";tmp_form.title.focus();return false;}if(tmp_form.content.value == ""){err.innerHTML = "内容不能为空!";err.style.color = "red";err.style.fontSize = "9px";tmp_form.title.focus();return false;}return true;}</script></head><body><form method="post" action="" name="form1" onsubmit="return check_form(this);"><p><label for="title">标题:</label><input type="text" name="title" id="title"></p><p><label for="content">内容:</label><textarea rows="10" cols="30" name="content" id="content"></textarea></p><p><input type="submit" value="提 交"></p><p id="error_tips"> </p></form></body></html>
一般推荐使用标签方式,既可以醒目的提醒用户,又不会因为频繁跳出的提示框造成用户体验下降;另外,由于html标签不能使用name属性,只能使用id属性访问,所以通过document对象的getElementById方法,获取到保存至变量err中,方便使用。在tmp_form对象中是无法直接访问标签error_tips的。