如何利用jQuery进行简单表单验证

时间:2021-12-12 21:41:56

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>蚂蚁部落</title>
<style type="text/css">
body {
    font-size: 11px
}
#divLogin {
    margin: 15% 0 0 15%
}
#divLogin fieldset {
    width: 300px;
    padding: 0px;
    margin: 0px
}
#divLogin fieldset h3 {
    margin: 0px;
    padding: 5px;
    background-color: #eee
}
#divLogin fieldset .content {
    padding: 20px;
    line-height: 2.6em
}
#divLogin fieldset .content .btnCenter {
    text-align: center
}
.txt {
    border: #666 1px solid;
    padding: 2px;
    width: 180px;
    margin-right: 3px
}
.btn {
    border: #666 1px solid;
    padding: 2px;
    width: 60px;
 filter: progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr=#ffffff, EndColorStr=#ECE9D8)
}
</style>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
   $(document).ready(function(){
      $("#Button1").click(function() { //按钮点击事件
         var $name = $("#txtName"); //用户名
         var $pass = $("#txtPass"); //密码
         if ($name.val() == "")
        {
            alert("用户名不能为空!");
            $name.focus();
            return false;
         }
         else
        {
            alert("密码不能为空!");
            $pass.focus();
            return false;
         }
      })
   })
</script>
</head>
<body>
<div id="divLogin">
  <fieldset>
    <h3>用户登录</h3>
    <div class="content">
      <div>用户:
        <input id="txtName" type="text" class="txt" />
      </div>
      <div>密码:
        <input id="txtPass" type="password" class="txt"/>
      </div>
      <div class="btnCenter">
        <input id="Button1" type="button" value="登录" class="btn" />
        <input id="Reset1" type="reset" value="取消" class="btn" />
      </div>
    </div>
  </fieldset>
</div>
</body>

</html>

以上代码实现了基本的表单验证功能,