基于jQuery实现表单提交验证

时间:2022-09-09 10:41:19

html表单代码:

复制代码 代码如下:

   <form method="post" action="">
       <div class="int">
          <label for="username">用户名:</label>
          <input type="text" id="username" class="required"/>
       </div>
       <div class="int">
           <label for="username">邮箱:</label>
           <input type="text" id="email" class="required"/>
       </div>
       <div class="int">
           <label for="username">个人资料:</label>
           <input type="text" id="personinfo"/>
       </div>
       <div class="sub">
           <input type="submit" value="提交" id="send"/>
           <input type="reset" id="res"/>
       </div>
   </form> 

 

jQuery代码:

复制代码 代码如下:

          $(function(){
            $("form :input.required").each(function(){
                var $required = $("<strong class='high'>*</strong>");
                //$(this).parent().append($required);  //追加到文档中
                $(this).parent().prepend($required);
            });
            $('form :input').blur(function(){
                var $parent = $(this).parent();
                if($(this).is('#username')){
                   if(this.value==""||this.value.length<6){
                      var errorMsg = '请输入至少6位的用户名';
                      $parent.append('<span class="formtips onError">'+errorMsg+'</span>');
                   }else{
                       var okMsg = '输入正确';
                       $parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
                   }
                }
                if($(this).is('#email')){
                    if(this.value==""||(this.value!=""&&!/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value))){
                        var errorMsg = '请输入正确的E-mail地址';
                        $parent.append('<span class="formtips onError">'+errorMsg+'</span>');
                    }else{
                        var okMsg = '输入正确';
                        $parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
                    }
                }
            });
            $("form :input").focus(function(){
                var $parent = $(this).parent();
                $parent.find(".formtips").remove();
            });
            $("#send").click(function(){
               var $parent = $(this).parent().parent();
               $parent.find(".formtips").remove();
               $("form .required:input").trigger('blur');
               var numError = $('form .onError').length;
               if(numError){
                  return false;
               }
            });
            $("#res").click(function(){
                var $parent = $(this).parent().parent();
                $parent.find(".formtips").remove();
            });
        });

 

代码很简单,也很易懂,小伙伴们直接拿走用吧,这里就不详细说明了。