jquery formValidate

1.jquery包的引入:

   引入jquery包:<script type="text/javascript" src=../../"/common/js/jquery/jquery.js'"></script>

 

2.添加校驗說明:

    主要使用的是javascript編寫的驗證庫——jQuery.Validate,這個驗證庫是屬於jQuery的插件。

引入:

 <script type="text/javascript" src=../../"/common/js/jquery/jquery.validate.pack.js"></script>

jQuery.Validate是監控form的,在任何提交表單的操作前jQuery.Validate都會檢測表單裏的輸入項是否滿足規則,滿足才允許提交。所以需要在jQuery(document).ready()時爲form進行驗證註冊,格式: $(“#formid”).validate(jsonobj)。

其中formid是文件中form表單的id,jsonobj包含兩個屬性:rules和messages,rules用來指明每個字段上添加的校驗規則,messages用來說明相應的校驗出錯時對應的提示語。

messages爲非必須,如果自己不定義該屬性,會採用默認的提示。

例如/test/validate/formvalidate.jsp:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />

<title>表單校驗</title>

<script type="text/javascript" src=../../"/common/jquery.js"></script>

<script type="text/javascript" src=../../"/common/jquery.validate.pack.js"></script>

<script type="text/javascript" src=../../"/common/jquery.form.js"></script>

</head>

<body>

    <form id="test">

        <input name="nameput" type="text" size="20"/>

        <input name="submit" type="submit" value="提交"/>

    </form>

    <script type="text/javascript">

        $("#test").validate({

            rules:{

                "nameput":{

                    required:true,

                    minlength:3,

                    maxlength:10

                }  

            },

            messages:{

                "nameput":{

                    required:"不能爲空",

                    minlength:jQuery.format("長度不小於{0}"),

                    maxlength:jQuery.format("長度不大於{0}")

                }

            }

        })

    </script>

</body>

</html>

注意:nameput是input標籤的name。

Required、minlength、maxlength都是jQuery校驗的內置驗證方式。jQuery內置驗證方式參考jQuery.validate.js的API。

 

3.自定義驗證方式

下面是自定義的驗證方式:

$.validator.addMethod("stringlength", function(value, element,params) {    

//默認值 : {trim:true,minLength:-1,maxLength:-1

    params = $.extend([true,-1,-1],params); //對於默認參數支持

    if(params[0]){  //過濾首尾空格

        value=$.trim(value);

    }

    value = value.replace(/<(?:.)*?>/g,""); //驗證時過濾標籤

    return this.optional(element) || ((params[1]<0 || value.length>=params[1])&&(params[2]<0 || value.length<=params[2]));

}, jQuery.format("長度在{1}-{2}之間"));

例如home工程中的登錄校驗:

$('#loginform').validate({//登陸校驗

    rules:{

        "userAccount.userName":{

            "requiredstring":["true"],

            " requiredstring ":true,

            "stringlength":["true","3","40"]

        },

        "userAccount.userPwd":{

            "requiredstring":["true"],

            "stringlength":["true","1","20"]

        }

    },

    messages:{

        "userAccount.userName":{

            "requiredstring":"用戶名必填",

            "stringlength":jQuery.format("用戶名長度在{1}和{2}之間")

        },

        "userAccount.userPwd":{

            "requiredstring":"密碼不可以爲空",

            "stringlength":jQuery.format("密碼長度在{1}和{2}之間")

        }

    }

})

userAccount.userName是頁面對應的input的name,requiredstring、requiredstring、stringlength是自己定義的校驗,定義在/image/hi/common/js/zxwvalidate.js裏。

{1}、{2}等是rules裏面對應驗證方式的第幾個元素,從0開始。

簡單的實例:

$.validator.addMethod("twd", function(value, element,params) {    //默認值 : {trim:true,minLength:-1,maxLength:-1

          params = $.extend([true,-1,-1],params); //對於默認參數支持

          if(params[0]){

              value=$.trim(value);

          }

      })

      $("#test").validate({

          rules:{

              "nameput":{

                  "twd":[true,3,10]

              }  

          },

          messages:{

              "nameput":{

                  "twd":jQuery.format("長度在{1}和{2}之間")

              }

          }

       })

 

4.其他注意事項

    (1)校驗默認是在點擊提交submit的時候起作用.

    (2)如果缺少$().ready(function() {  }),校驗內容必須寫在表單的後面。

    (3)debug方法需要單獨寫或者rules和messages的後面,否則不會起作用。

   

附:

jQuery.Validate爲我們提供了3種驗證編寫方式,各有優缺點:

(1)在input對象中書寫class樣式指定驗證規則或屬性驗證規則:

如<input type=”text” class=”required”/>

最簡單、最便捷,提示消息使用jQuery.Validate的內置的消息(自定義擴展驗證規則也屬於此項),但是由於是以樣式名的方式進行驗證,導致了日後修改必須找到相應的input對象,同時無法使用高級驗證規則。

(2)在input對象中書寫class樣式,只不過書寫的方式改爲了JSON格式,但是這種方式提供了自定義驗證消息的支持:

如<input type=”text” class="{required:true,minlength:5,,messages:{required:'請輸入內容'}”/>

簡單、方便,但個人認爲有點臃腫,還是和第1條一樣和相對應的input對象糾纏在一起,並且還增加消息自定義,使得input對象變的更大了,干擾了頁面代碼的閱讀,但可以使用高級驗證規則(實際就是將第3種JS以JSON的格式放到具體的class中。

(3)使用純JS的方式:

如:

$().ready(function() { 
    $("#aspnetform").validate({ 
         rules: { 
         name: "required", 
         email: { 
                 required: true, 
                 email: true 
         }

     })

})

很好的解決了HTML和驗證規則的分離,就是書寫較爲麻煩,需要單獨寫JS腳本,但好處是可以統一驗證規範,將每個頁面的驗證規則都寫在頭部的腳本中,方便日後維護 

默認的提示

messages: {
required: "This field is required.",
remote: "Please fix this field.",
email: "Please enter a valid email address.",
url: "Please enter a valid URL.",
date: "Please enter a valid date.",
dateISO: "Please enter a valid date (ISO).",
dateDE: "Bitte geben Sie ein g眉ltiges Datum ein.",
number: "Please enter a valid number.",
numberDE: "Bitte geben Sie eine Nummer ein.",
digits: "Please enter only digits",
creditcard: "Please enter a valid credit card number.",
equalTo: "Please enter the same value again.",
accept: "Please enter a value with a valid extension.",
maxlength: $.validator.format("Please enter no more than {0} characters."),
minlength: $.validator.format("Please enter at least {0} characters."),
rangelength: $.validator.format("Please enter a value between {0} and {1} characters long."),
range: $.validator.format("Please enter a value between {0} and {1}."),
max: $.validator.format("Please enter a value less than or equal to {0}."),
min: $.validator.format("Please enter a value greater than or equal to {0}.")
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章