JavaWeb判断表单是否为空值
方法一:js判空
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表单判空</title>
</head>
<script type="text/javascript">
function show() {
//if(document.form.username.value.toString().trim().length <= 0)该方法也适用,就不另写了。
if(document.form.username.value==""){
document.form.username.focus();//光标显示的位置
alert("用户名不能为空!");
return false;
}
if(document.form.age.value==""){
document.form.age.focus();
alert("年龄不能为空!");
return false;
}
if(document.form.sex.value!="男"&&document.form.sex.value!="女"){
document.form.sex.focus();
alert("性别只能写'男'或者'女'");//注意双引号里面不能再用双引号,用单引号与转义字符都可以。不然会出现不报错的问题。
return false;
}
return true;
}
</script>
<body>
<form action="login.jsp" method="post" name="form">
<table border="1" >
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>年龄:</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td>性别:</td>
<td><input type="text" name="sex"></td>
</tr>
<tr>
<td><input type="submit" value="提交" onclick="return show()"></td>
<td><input type="reset" value="取消"></td>
</tr>
</table>
</form>
</body>
</html>
方法二:另写一个check.jsp判空
//获取之后判断输入框空值。省的麻烦就不一一写了,我就直接全部一起判断!
if(username==""||pass==""||rpass==""||yan==""||type==""){
out.print("<script>alert('用户名、密码、确认密码、验证码或者类型不能为空!请输入');window.location='register.jsp';</script>");
截图
第一次上手写,可能排版什么的会很简陋,大家有不了解的可以看看代码块里面的注释,大致写清楚了。