怎样用JavaScript编写客户端表单验证的代码?

客户端表单验证的simple2.htm页面代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>信息录入</title>
<script language="javascript">
function validate(){
if (document.getElementById("myname").value==""){
alert("请填写姓名!");
return false;
}
if(document.getElementById("password1").value!=document.getElementById("password2").value||document.getElementById("password1").value=""){
alert("请输入合法密码!");
return false;
}
}
</script>
</head>

<body>
<form action="simple2.jsp" method="post" onSubmit="validate()">
请输入姓名:
<input type="text" id="myname" name="myname"><br>
请输入密码:
<input type="password" id="password1" name="password1"><br>
确认密码:
<input type="password" id="password2" name="password2"><br>
<input type="submit" value="提交" onClick="validate()">
<input type="reset" value="复位">
</form>
</body>
</html>

页面提交到simple2.jsp,simple2.jsp的代码如下:

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>信息获取显示</title>
</head>

<body>
<%
String name=request.getParameter("myname");
String password=request.getParameter("password1");
out.println("你输入的姓名是:"+name+"<br>");
out.println("你输入的密码是:"+password);
%>
</body>
</html>

发现客户端验证代码没有作用,怎么写JavaScript代码和

表单里的代码呢?

js的话 直接if(myname==null){
alert(“请输入姓名”)//或者其他提示方式
return;
}

input if判断值获取

ajax

直接用if循环!

请参考:https://hovertree.com/front/3/

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>登录-何问起</title>
    <script language="javascript">
        function validate() {
            if (document.getElementById("myname").value == "") {
                alert("请填写姓名!");
                return false;
            }
            if (document.getElementById("password1").value != document.getElementById("password2").value || document.getElementById("password1").value == "") {
                alert("请输入合法密码!");
                return false;
            }
        }
    </script>
</head>

<body>
    <form action="https://www.csdn.net/" id="hovertreeform" method="post" onSubmit="validate()">
            请输入姓名:
        <input type="text" id="myname" name="myname"><br>
        请输入密码:
        <input type="password" id="password1" name="password1"><br>
        确认密码:
        <input type="password" id="password2" name="password2"><br>
        <input type="submit" value="提交" onclick="return validate()">
        <input type="reset" value="复位">
    </form>
</body>
</html>