JavaScript实现输入验证(简单的用户注册)

1.先写用户注册页面userrAdd.jsp

  <body>
  
   <center>
    <form name="f1" id="f1" action="userrAdd2.jsp" method="post" >
      <table border="0">
      <tr>
          <td><strong>用户名</strong>:</td>
          <td><input type="text" name="username" id="username" value="" maxlength="11"></td>
        </tr>
        <tr>
          <td><strong>手机号</strong>:</td>
          <td><input type="text" name="phonenumber" id="phonenumber" value="" maxlength="11"></td>
        </tr>
        <tr>
          <td><strong>密码:</strong></td>
          <td><input type="text" name="password" id="password" value="" maxlength="11"></td>
        </tr> 
        <tr>
          <td colspan="2" align="center"><input type="button" value="注册 " onclick="validate()"></td>/////////注意此处提交按钮为button,在javascript中提交
        </tr>
      </table>
    </form>



</center>
  </body>
</html>

2.然后写javascript,也在userrAdd.jsp中写在</head>前

<script type="text/javascript">
	function validate()
    {
    var username=document.forms[0].username.value;
    var phonenumber=document.forms[0].phonenumber.value;
    var password=document.forms[0].password.value;
    
    if(username.length<2){
    	alert("请输入合法用户名!");//////////////////////////////////////////验证用户名
    }
    else if(phonenumber.length<11){
    	alert("您的手机号应该为十一位!");////////////////////////////////////验证手机号
    }
    else if(password.length<6){
    	alert("密码至少六位!");////////////////////////////////////////////验证密码
    }
    else{
    	document.forms[0].submit();//////////////////////////////////////提交到userrAdd2.jsp
    }
    }
	</script>

3.注册到数据库:userrAdd2.jsp

<body>
   <%
   request.setCharacterEncoding("utf-8");
   String username=request.getParameter("username");
    String phonenumber=request.getParameter("phonenumber");
    String password=request.getParameter("password");
    
	Connection con = null;    
	Statement stmt = null;    
	ResultSet rs = null;  
	
	String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=student;user=sa;password=1";//sa身份连接
	
	Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 
	con = DriverManager.getConnection(url);  
	stmt = con.createStatement();  
	String SQL = "insert into userr values('"+username+"','"+phonenumber+"','"+password+"')";    
	stmt.execute(SQL);  
%>
注册成功
  </body>

4.结果截图

原文地址:https://www.cnblogs.com/feifeishi/p/5312286.html