在登入頁面中js進行正則驗證電話號碼和郵箱地址,並使用ajax進行使用者ID的資料庫驗證

mlinge-奮鬥吧發表於2012-08-09

本文說的是在登入頁面中使用js進行正則驗證並使用ajax進行使用者ID的資料庫驗證,另外也加入鍵盤監聽。


先看一下登入的jsp頁面程式碼

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="org.ml.drp.sysmgr.domain.*"%>
<%@ page import="org.ml.drp.sysmgr.manager.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
String command = request.getParameter("command"); 
if("addUser".equals(command)){
	if(UserManager.getInstance().findUserById(request.getParameter("userId"))!=null){
		out.write("<font color=red>使用者"+request.getParameter("userId")+"已經存在</font>");  
	}else{
		User user = new User();
		user.setUserId(request.getParameter("userId"));
		user.setUserName(request.getParameter("userName"));
		user.setPassword(request.getParameter("password"));
		user.setContactTel(request.getParameter("contactTel"));
		user.setEmail(request.getParameter("email"));
		if(UserManager.getInstance().addUser(user)){
			out.write("<font color=red>使用者資訊新增成功</font>"); 
		}else{
			out.write("<font color=red>新增使用者過程中出現異常</font>");  
		}
	}
}
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>新增使用者</title>
		<link rel="stylesheet" href="../style/drp.css">
		<script src="../script/client_validate.js"></script>
		<script type="text/javascript">
		function goBack() {
			window.self.location="user_maint.html";
		} 
		function addUser() {
			//驗證使用者程式碼 
			var userId = document.getElementById("userId");
			var userIdValue = userId.value;			
			if(!(/^[a-zA-Z]+[a-zA-Z0-9]*$/.test(trim(userIdValue))&&/^[a-zA-Z0-9]{4,6}$/.test(trim(userIdValue)))){
				alert("使用者程式碼必須以字母開頭,並且為4-6位!");  
				userId.focus();
				userId.select();
				return;
			}
			/*
			if(trim(userIdValue)==""){
				alert("使用者程式碼不能為空 !"); 
				userId.focus();
				userId.select();
				return;
			}
			if(trim(userIdValue).length<4){
				alert("使用者程式碼至少為4位!"); 
				userId.focus();
				userId.select(); 
				return;
			}
			*/ 
			//驗證使用者名稱 
			var userName = document.getElementById("userName");
			var userNameValue = userName.value;
			if(trim(userNameValue)==""){
				alert("使用者名稱不能為空 !"); 
				userName.focus();
				userName.select();
				return;
			}
			//驗證密碼 
			var password = document.getElementById("password");
			var passwordValue = password.value;
			if(trim(passwordValue)==""){
				alert("密碼不能為空 !"); 
				password.focus();
				password.select();
				return; 
			}
			if(trim(passwordValue).length<6){
				alert("使用者密碼至少6位!"); 
				password.focus();
				password.select();
				return;
			}
			//驗證電話 
			var contactTel = document.getElementById("contactTel");
			var contactTelValue = contactTel.value;
			if(trim(contactTelValue)!=""){
				var pattern=/^(13[0-9]|15[0-9]|18[8|9])\d{8}$/; 
				var flag = pattern.test(contactTelValue);
				if(!flag){
					alert("聯絡電話格式不正確!"); 
					contactTel.focus();
					return;
				}
			}
			//驗證郵箱 		
			var email = document.getElementById("email");
			var emailValue = email.value;  			
        if(trim(emailValue)!=""){
	 			var pattern1 = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; 
	  			var flag = pattern1.test(emailValue);  
				if(!flag) 
		      {  
		    		alert("Email地址不合法!"); 
					email.focus();
					email.select();
			      return;  				
				}
			} 
			var form = document.getElementById("userForm");
			form.submit();
		} 
		function init(){
			document.getElementById("userId").focus();//第一個輸入框獲取得焦點 
		}
		//鍵盤按下監聽 
		function keyPress(nextId){ 
			if(window.event.keyCode==13){//當按下的是Enter鍵的時候 
				document.getElementById(nextId).focus();
			}
		}
		var xmlHttp;
		function createXMLHttpRequest(){
			if(window.XMLHttpRequest){
				xmlHttp = new XMLHttpRequest();
			}else if(window.ActiveXObject){
				xmlHttp = new window.ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		
		/*
        //方式一
        function checkUserId(userId){
            if(trim(userId.value)!=""){
                createXMLHttpRequest();//建立Ajax核心物件XMLHttpRequest
                var url = "user_validate.jsp?userId="+trim(userId.value) + "&time="+new Date().getTime();
                //設定請求方式為get,設定 url請求,設定為非同步提交 
                xmlHttp.open("get",url,true);
                //將方法地址賦值給屬性 
                xmlHttp.onreadystatechange=callback;
                //將設定的資訊傳送給Ajax引擎 
                xmlHttp.send(null);
            }{
                document.getElementById("userIdSpan").innerHTML="<font color='red'>使用者程式碼不能為空</font>";
            }  
        }
        function callback(){
            if(xmlHttp.readyState==4){//響應完成 
                if(xmlHttp.status==200){//請求成功 
                    var userIdSpan = document.getElementById("userIdSpan"); 
                    userIdSpan.innerHTML=   xmlHttp.responseText  
                }else{
                    alert("使用者程式碼驗證請求失敗")
                }
            }
        }
        */
        //方式二 
        function checkUserId(userId){
            if(trim(userId.value)!=""){
                createXMLHttpRequest();//建立Ajax核心物件XMLHttpRequest
                var url = "user_validate.jsp?userId="+trim(userId.value) + "&time="+new Date().getTime();
                //設定請求方式為get,設定 url請求,設定為非同步提交 
                xmlHttp.open("get",url,true);
                //將方法地址賦值給屬性 
                xmlHttp.onreadystatechange=function(){//使用匿名物件進行 
                    if(xmlHttp.readyState==4){//響應完成 
                        if(xmlHttp.status==200){//請求成功 
                            var userIdSpan = document.getElementById("userIdSpan"); 
                            userIdSpan.innerHTML=   xmlHttp.responseText  
                        }else{
                            alert("使用者程式碼驗證請求失敗")
                        }
                    }
                };
                //將設定的資訊傳送給Ajax引擎 
                xmlHttp.send(null);
            }{
                document.getElementById("userIdSpan").innerHTML="<font color='red'>使用者程式碼不能為空</font>";
            }  
        } 

	</script>
	</head>

	<body class="body1" onload="init()">
		<form action="#" name="userForm" target="_self" id="userForm" method="post">
			<div align="center"> 
				<table width="95%" border="0" cellspacing="2" cellpadding="2">
					<tr>
						<td>  
							<input type="hidden" name="command" value="addUser">
						</td>
					</tr>
				</table>
				<table width="95%" border="0" cellspacing="0" cellpadding="0"
					height="25">
					<tr>
						<td width="522" class="p1" height="25" nowrap>
							<img src="../images/mark_arrow_03.gif" width="14" height="14">
							 
							<b>系統管理>>使用者維護>>新增</b>
						</td>
					</tr>
				</table>
				<hr width="97%" align="center" size=0>
				<table width="95%" border="0" cellpadding="0" cellspacing="0">
					<tr>
						<td width="22%" height="29">
							<div align="right">
								<font color="#FF0000">*</font>使用者程式碼: 
							</div>
						</td>
						<td width="78%">
							<input name="userId" type="text" class="text1" id="userId"
								size="10" maxlength="10" onkeypress="keyPress('userName')" onblur="checkUserId(this)"> 
							<span id="userIdSpan" ></span>
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								<font color="#FF0000">*</font>使用者名稱稱: 
							</div>
						</td>
						<td>
							<input name="userName" type="text" class="text1" id="userName"
								size="20" maxlength="20" onkeypress="keyPress('password')">
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								<font color="#FF0000">*</font>密碼: 
							</div>
						</td>
						<td>
							<label>
								<input name="password" type="password" class="text1"
									id="password" size="20" maxlength="20" onkeypress="keyPress('contactTel')">
							</label>
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								聯絡電話: 
							</div>
						</td>
						<td>
							<input name="contactTel" type="text" class="text1"
								id="contactTel" size="20" maxlength="20" onkeypress="keyPress('email')">
						</td>
					</tr>
					<tr>
						<td height="26">
							<div align="right">
								email: 
							</div>
						</td>
						<td>
							<input name="email" type="text" class="text1" id="email"
								size="20" maxlength="20" onkeypress="keyPress('btnAdd')">
						</td>
					</tr>
				</table>
				<hr width="97%" align="center" size=0>
				<div align="center">
					<input name="btnAdd" class="button1" type="button" id="btnAdd"
						value="新增" onClick="addUser()">
					    
					<input name="btnBack" class="button1" type="button" id="btnBack"
						value="返回" onClick="goBack()" />
				</div>
			</div>
		</form>
	</body>
</html>

執行驗證資料庫的時候的程式碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ page import="org.ml.drp.sysmgr.manager.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>"> 
    <title>My JSP 'user_validate.jsp' starting page</title> 
  </head>
  
  <body>
   <%
   		String userId = request.getParameter("userId").trim();
   		System.out.println(userId);
   		if(UserManager.getInstance().findUserById(userId)!=null){
   			out.print("<font color='red'>使用者程式碼已存在</font>");
   		}else{
   			out.print("<font color='green'>使用者程式碼可使用</font>"); 
   		}
    %>
  </body>
</html>

資料庫的管理操作類如下:

package org.ml.drp.sysmgr.manager;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import org.ml.drp.sysmgr.domain.User;
import org.ml.drp.util.DbUtil;

public class UserManager {

	private static UserManager instance = null;
	/**
	 * 私有化的無參構造方法
	 */
	private UserManager(){
		
	}
	/**
	 * 取得UserManager例項化物件
	 * @return
	 */
	public static UserManager getInstance(){
		if(instance==null){
			instance = new UserManager();
		}
		return instance;
	}
	/**
	 * 新增使用者資訊
	 * @param user
	 * @return
	 */
	public boolean addUser(User user){
		boolean flag = false; 
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = "insert into t_user(user_id,user_name,password,contact_tel,email,create_date) values(?,?,?,?,?,?)"; 
		try {
			conn = DbUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, user.getUserId());
			pstmt.setString(2, user.getUserName());
			pstmt.setString(3, user.getPassword());
			pstmt.setString(4, user.getContactTel());
			pstmt.setString(5, user.getEmail());
			pstmt.setTimestamp(6, new Timestamp(new Date().getTime()));
			if(pstmt.executeUpdate()>0){
				flag = true;//新增成功
			}
		} catch (SQLException e) { 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DbUtil.close(conn);//關閉資料庫連線
			DbUtil.close(pstmt);//關閉prepareStatementd物件
		} 
		return flag;
	}
	/**
	 * 根據使用者ID查詢使用者
	 * @param userId
	 * @return
	 */
	public User findUserById(String userId){
		User user = null;
		String sql = "select user_name,password,contact_tel,email,create_date from t_user where user_id=?";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn = DbUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, userId);
			rs = pstmt.executeQuery();
			if(rs.next()){
				user = new User();
				user.setUserId(userId);
				user.setUserName(rs.getString(1));
				user.setPassword(rs.getString(2));
				user.setContactTel(rs.getString(3));
				user.setEmail(rs.getString(4));	
				user.setCreateDate(rs.getTimestamp(5));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DbUtil.close(conn);//關閉資料庫連線
			DbUtil.close(pstmt);//關閉prepareStatementd物件
		}   
		return user;
	}
	
	
}
這裡只是進行了簡單的記錄,只貼上了程式碼,沒做過多說明,有興趣的可以慢慢看吧,還有如果要看資料庫實現資料庫連線操作類的程式碼的可以看看這篇http://blog.csdn.net/cselmu9/article/details/7844235文章,這裡面有完整資料庫連線操作程式碼,這裡就不貼出來了。

相關文章