jquery驗證大全

這是我參與8月更文挑戰的第12天,活動詳情查看:8月更文挑戰javascript

jQuery驗證及限制java

jQuery驗證及限制

綁定鍵盤監聽事件

$(document).on("keypress", ".txt-valid-len", function (e) 
	{
		return (this.value.length < $(this).attr("maxlength"));
	});

複製代碼

輸入框設置

  • 而後咱們只須要在input中添加txt-valid-len這個class屬性。而且加入maxlength屬性指定長度就能夠了。jquery

<input type="text" id="user_name" name="name" class="form-control txt-valid-len" maxlength="11" />
複製代碼
  • 上面的代碼的意思就是這個輸入框長度限制在11位,超過11位就不顯示了。若是想在超過11位進行提示。能夠擴展上面的監聽事件。

jquery表單提交驗證

  • 在開發中咱們前臺常常須要在與後臺交互前進行相關數據的驗證。這樣能夠減小服務端的壓力。下面咱們來看看jquery給咱們提供的表單驗證的方法。

引入腳本文件

jquery.min.js
jquery.validate.js
複製代碼
  • 這兩個js在官網的jQuery中都是包含的,直接下載引入就好了。ajax

  • 有了這兩個js咱們還須要頁面上的form表單。表單就是咱們日常的表單。json

<form id="myform" method="post" action="#">
      <p>
          <label for="myname">用戶名:</label>
          <!-- id和name最好同時寫上 -->
          <input  id="myname" name="myname" />
      </p>
      <p>
          <label for="age">年齡:</label>
          <input id="age" name="age" />
      </p>
      <p>
          <label for="email">E-Mail:</label>
          <input id="email" name="email" />
      </p>
      <p>
          <label for="password">登錄密碼:</label>
          <input id="password" name="password" type="password" />
      </p>
      <p>
          <label for="confirm_password">確認密碼:</label>
          <input  name="confirm_password" type="password" />
      </p>
      <p>
          <input class="submit" type="submit" value="當即註冊" />
      </p>
</form>
複製代碼

自定義js實現表單驗證(利用jQuery提供內置方法)

  • 首先咱們經過jQuery提供的選擇器找到咱們須要驗證的表單
$("#myform").validate();
複製代碼
  • 就這樣咱們就完成了表單驗證。固然啦,到這裏只是架子打好了。下面咱們開始在validate中填寫咱們的驗證規則了。
$("#myform").validate({
        debug: true, //調試模式取消submit的默認提交功能   
        //errorClass: "label.error", //默認爲錯誤的樣式類爲:error   
        focusInvalid: false, //當爲false時,驗證無效時,沒有焦點響應  
        onkeyup: false,   
        submitHandler: function(form){   //表單提交句柄,爲一回調函數,帶一個參數:form   
            alert("提交表單");   
            form.submit();   //提交表單   
        },   
        
        rules:{
            myname:{
                required:function(element){
                    if( $("#age").val() < 13){
                    	return true;
                    }
                    else{
                    	return false;
                    }
                }
            },
            email:{
                required:true,
                email:true
            },
            password:{
                required:true,
                rangelength:[3,10]
            },
            confirm_password:{
                equalTo:"input[name=password]"
            }                    
        },
        messages:{
            myname:{
                required:"必填"
            },
            email:{
                required:"<span style='color:red;'>只容許輸入整數。</span>",
                email:"E-Mail格式不正確"
            },
            password:{
                required: "不能爲空",
                rangelength: $.validator.format("密碼最小長度:{0}, 最大長度:{1}。")
            },
            confirm_password:{
                equalTo:"兩次密碼輸入不一致"
            }                                    
        }
                  
    });
複製代碼
  • 其中的rules就是咱們驗證規則內容。其中的myname,email...是咱們form須要驗證的控件的name屬性值(並非ID屬性值),還有咱們的提示信息能夠作的花哨一點加入樣式
<span style='color:red;'>只容許輸入整數。</span>
複製代碼
  • 至於這些驗證規則咱們能夠在jquery-validate.js中找到。裏面messages屬性的提示信息咱們都是能夠用來作驗證的.

動態決定驗證規則

  • 上面的myname的required的驗證是根據id=age的input框的值得變化決定的,就是說你輸入的年齡小於13歲myname是須要驗證的。大於則反之。若是你想作的像更美化咱們能夠在年齡input中綁定一個失去焦點的時間(blur),在輸入完年齡咱們就立馬去驗證myname的input框的規則,經過調用
$("#myname").valid();
複製代碼
  • 就會去按照咱們的規則去驗證myname這個字段的input的值。

經過遠程進行驗證

前臺

  • 對上面的進行以下的修改,其中remote就是咱們的遠程請求,該請求返回的true,則驗證經過,false反之。
$("#myform").validate({  
  rules: {  
    email: {  
      required: true,
      email: true,
      remote: {
          type:"post",
          dataType: "json",
          contentType : "application/json",
          url:"/adminManage/email.bsh"
      }  
    }  
  }  
}); 
複製代碼

後臺

  • 這的注意的是remote這裏的請求格式有些要求,這個url返回的數據必須是json格式的。可是後臺只能返回string或者boolean類型的數據。若是返回的是string內容的json,那麼string是true則驗證經過,若果不是true則驗證提示就是你返回的string內容。若是是boolean,是true則驗證經過,false驗證失敗。
@RequestMapping("/email.bsh")
    @ResponseBody
    public Object email(HttpServletRequest request,HttpServletResponse response) 
    {
        
        return "已經存在";
    }
複製代碼
  • 前臺提示已經存在,會覆蓋前臺默認的提示內容
@RequestMapping("/email.bsh")
@ResponseBody
public Object email(HttpServletRequest request,HttpServletResponse response) 
{
    
    return "true";
}
複製代碼
  • 驗證經過
@RequestMapping("/email.bsh")
@ResponseBody
public Object email(HttpServletRequest request,HttpServletResponse response) 
{
    
    return true;
}
複製代碼
  • 驗證經過
@RequestMapping("/email.bsh")
@ResponseBody
public Object email(HttpServletRequest request,HttpServletResponse response) 
{
    
    return false;
}
複製代碼
  • 驗證失敗,前臺將提示默認的信息

參考網址markdown

驗證提示信息的顯示位置

  • 在上面一節咱們詳細介紹了驗證的規則及提示實現。那麼提示信息的位置有時候也是很重要的,咱們控制的好的話界面會很美觀的。
var validator = $("#myform").validate({  
        debug: true,       //調試模式取消submit的默認提交功能  
        errorClass: "haha",//默認爲錯誤的樣式類爲:error  
        focusInvalid: false,  
        onkeyup: false,  
        submitHandler: function(form){   //表單提交句柄,爲一回調函數,帶一個參數:form  
            alert("提交表單");  
            //form.submit();   提交表單  
        },  
        rules: {           //定義驗證規則,其中屬性名爲表單的name屬性  
            username: {  
                required: true,  
                minlength: 2,  
                remote: "uservalid.jsp"  //傳說當中的ajax驗證  
            },  
            firstpwd: {  
                required: true,  
                //minlength: 6  
                rangelength: [6,8]  
            },  
            secondpwd: {  
                required: true,  
                equalTo: "#password"  
            },  
            sex: {  
                required: true  
            },  
            age: {  
                required: true,  
                range: [0,120]  
            },  
            email: {  
                required: true,  
                email: true  
            },  
            purl: {  
                required: true,  
                url: true  
            },  
            afile: {  
                required: true,  
                accept: "xls,doc,rar,zip"  
            }  
        },  
        messages: {       //自定義驗證消息  
            username: {  
                required: "用戶名是必需的!",  
                minlength: $.format("用戶名至少要{0}個字符!"),  
                remote: $.format("{0}已經被佔用")  
            },  
            firstpwd: {  
                required: "密碼是必需的!",  
                rangelength: $.format("密碼要在{0}-{1}個字符之間!")  
            },  
            secondpwd: {  
                required: "密碼驗證是必需的!",    
                equalTo: "密碼驗證須要與密碼一致"  
            },  
            sex: {  
                required: "性別是必需的"  
            },  
            age: {  
                required: "年齡是必需的",  
                range: "年齡必須介於{0}-{1}之間"  
            },  
            email: {  
                required: "郵箱是必需的!",  
                email: "請輸入正確的郵箱地址(例如 myemail@163.com)"  
            },  
            purl: {  
                required: "我的主頁是必需的",  
                url: "請輸入正確的url格式,如 http://www.domainname.com"  
            },  
            afile: {  
                required: "附件是必需的!",  
                accept: "只接收xls,doc,rar,zip文件"  
            }  
        },  
        errorPlacement: function(error, element) {  //驗證消息放置的地方  
            error.appendTo( element.parent("td").next("td") );  
        },  
        highlight: function(element, errorClass) {  //針對驗證的表單設置高亮  
            $(element).addClass(errorClass);  
        },  
        success: function(label) {    
                    label.addClass("valid").text("Ok!")    
            }    
          
        /*, 
        errorContainer: "#error_con",               //驗證消息集中放置的容器 
        errorLabelContainer: "#error_con ul",       //存放消息無序列表的容器 
        wrapper: "li",                              //將驗證消息用無序列表包圍 
        validClass: "valid",                        //經過驗證的樣式類 
        errorElement: "em",                         //驗證標籤的名稱,默認爲:label 
        success: "valid"                            //驗證經過的樣式類 
        */  
    });
複製代碼

重構規則

不論何時,當你的表單中的多個字段含有相同的驗證規則及驗證消息,重構規則能夠減小不少重複。使用 addMethod 和 addClassRules 將很是有效果。
假使已經重構了以下規則:app

// alias required to cRequired with new message  
$.validator.addMethod("cRequired", $.validator.methods.required,  
  "Customer name required");  
// alias minlength, too  
$.validator.addMethod("cMinlength", $.validator.methods.minlength,   
  // leverage parameter replacement for minlength, {0} gets replaced with 2  
  $.format("Customer name must have at least {0} characters"));  
// combine them both, including the parameter for minlength  
$.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 }); 

<input name="customer1" class="customer" />  
<input name="customer2" class="customer" />  
<input name="customer3" class="customer" /> 
複製代碼

adMethod

addMethod( name, method, [message] )
返回:undefineddom

參數 name 類型:String
要添加的方法名,用於標識和引用,必須是一個有效的javascript標識符。koa

參數 method 類型:Callback 方法的實現部分,返回true若是表單元素經過驗證。jsp

參數 message(Optional) 類型:String, Function 該方法的默認驗證消息。能夠用 jQuery.validator.format(value) 方法建立。若是未定義該參數,則使用本地已存在的驗證消息,另外,必須爲指定的表單元素定義驗證消息。

說明:添加一個用戶自定義的驗證方法。它由方法名(必須是一個合法的javascript標識符)、基於javascript的函數及默認的驗證消息組成。

addClassRules( name, rules ) 返回:undefined

參數 name 類型:String 要添加的樣式規則名。

參數 rules 類型:Options 規則選項。

說明:添加一個複合的樣式驗證方法。對於將多個聯合使用的規則重構進單個樣式中很是有用。

相關文章
相關標籤/搜索