1. 程式人生 > >jsp表單提交前端驗證

jsp表單提交前端驗證

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>login</title>
<script src="static/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
	function myfunction(){
		var name=document.getElementById("name").value;
		var pass=document.getElementById("password").value;
		var radio=$("input[name='role']:checked").val();
		if(name==''){
			alert("使用者名稱不能為空");
			//window.location.reload();
            //阻止表單提交
			return false;
		}
		if(pass==''){
			alert("密碼不能為空");
			//window.location.reload();
			return false;
		}
		if(radio==null){
			alert("你還未選中任何角色");
			//window.location.reload();
			return false;
		}
		return true;
	}
</script>
</head>
<body>
    <-- 此處可以寫作控制器對映地址:test/login--->
	<form action="success.jsp" method="post">
		姓名:<input type="text" id="name" name="name"/></br>
		密碼:<input type="password" id="password" name="password"/></br>
		<input type="radio" name="role" value="teacher"/>老師
		<input type="radio" name="role" value="student"/>學生</br>
    <--此處一定有return,否則表單阻止提交後還是會跳轉(不太清楚原理。)-->
		<input type="submit" value="登入" onclick="return myfunction()"/>
		<input type="reset" value="重置"/></br>
	</form>
</body>
</html>

判斷單選框是否被選中

1、利用獲取選中值判斷選中

/*------判斷radio是否有選中,獲取選中的值--------*/
    var val=$('input:radio[name="sex"]:checked').val();
    if(val==null){
          alert("什麼也沒選中!");
          return false;
     }
      else{
          alert(val);
      }

2、使用checked屬性判斷選中

/*------radio不能用“checked”相等來判斷,只用用true來判斷--------*/
  if ($(this).attr("checked")) {
        alert("選中了");
      }

 

jsp本頁面判斷text是否為空

1. 使用document.getElementById("username").value來判斷其值是否為空

2.EL表示式

<%@ taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
在頁面上可以用C標籤.
<c:if test="${empty str}">  str為空</c:if><c:if test="${not empty str}">  str不為空
</c:if>
或者:
<c:choose><c:when test="${empty  字元變數}">
 字元變數為空</c:when><c:otherwise>
 字元變數不為空
</c:otherwise>
</c:choose>