jQuery Validate(一)


jQuery Validate 插件為表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單。

但是在學習的過程中,我也遇到了疑惑,網上的很多例子貌似都是依賴jquery.metadata.js這個庫,然后在標簽里寫成class=”required remote” 這樣的形式,class本身是呈現樣式的,現在被附上各種校驗的規則,看上去有些亂。那如果不依賴jquery.metadata.js,又該怎么寫。

1、只引入jquery.js(具體版本自己選擇)和jquery.validate.js

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery.validate.js"></script>
<script>
    $().ready(function() {
        $("#registerForm").validate();
    });
</script>

</head>
<body>
    <form id="registerForm" method="get" action="">
        <fieldset>
            <p>
                <label for="cusername">用戶名</label> 
                <input id="cusername" name="username" type="text" required="true" rangelength="[2,10]">
            </p>
            <p>
                <label for="cpassword">密碼</label>
                <input id="cpassword" name="password" type="password" required="true" minlength="6">
            </p>
            <p>
                <label for="cconfirmpassword">確認密碼</label> 
                <input id="cconfirmpassword" name="confirmpassword" type="password" required="true" equalTo="#cpassword">
            </p>
            <p>
                <label for="cemail">郵箱</label> 
                <input id="cemail" name="email" required="true" email="true"> </input>
            </p>
            <p>
                <input type="submit" value="提交">
            </p>
        </fieldset>
    </form>
</body>
</html>
JV1.HTML

事實證明,只引入上面的兩個JS文件也能完成簡單的表單驗證。

2、不過由於默認的提示信息是英文的,為了能有一個友好的提示,所以,接下來要做的就是讓提示信息顯示成中文了。

方法一、通過javascript自定義提示信息。

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery.validate.js"></script>
<script>
    $().ready(function() {
        $("#registerForm").validate({
            rules : {
                username : {
                    required : true,
                    rangelength:[2,10]
                },
                password : {
                    required : true,
                    minlength:6
                },
                confirmpassword : {
                    required : true,
                    equalTo:"#cpassword"
                },
                email : {
                    required : true,
                    email : true
                }
            },
            messages : {
                username : {
                    required : '請輸入姓名',
                    rangelength:'長度在 {0} 到 {1} 之間'
                },
                password : {
                    required : '請輸入密碼',
                    minlength:'密碼不能少於 {0}位'
                },
                confirmpassword : {
                    required : '請再次輸入密碼',
                    equalTo:'兩次輸入的密碼不一致'
                },
                email : {
                    required :'請輸入郵箱',
                    email : '請輸入有效的電子郵件地址'
                }
            }
        });
    });
</script>

</head>
<body>
    <form id="registerForm" method="get" action="">
        <fieldset>
            <p>
                <label for="cusername">用戶名</label> 
                <input id="cusername" name="username" type="text"/>
            </p>
            <p>
                <label for="cpassword">密碼</label> 
                <input id="cpassword" name="password" type="password"/>
            </p>
            <p>
                <label for="cconfirmpassword">確認密碼</label> 
                <input id="cconfirmpassword" name="confirmpassword" type="password"/>
            </p>
            <p>
                <label for="cemail">郵箱</label>
                <input id="cemail" name="email" type="email"/>
            </p>
            <p>
                <input type="submit" value="提交">
            </p>
        </fieldset>
    </form>
</body>
</html>
JV2-1.HTML

首先這里有一個方法調用: $("#registerForm").validate([options]) ,這是用來驗證選擇的表單,方法的參數是可選項,可以輸入0個或者多個鍵值對(key/value),這個方法是為了處理例如:submit , focus ,  keyup , blur, click 觸發驗證的,對象是整個表單的元素,或者是單個元素,使用 rules 和 messages 定義驗證的元素,使用errorClass, errorElement, wrapper, errorLabelContainer, errorContainer, showErrors, success, errorPlacement, highlight, unhighlight, ignoreTitle去控制非法元素的錯誤信息顯示。其中rules里也可以輸入0個或者多個鍵值對,他的key對應的是元素的name屬性值,例如username,confirmpassword等等。而他的value里則是一些驗證規則。messages同rules一樣可以輸入0個或者多個鍵值對,他的key也是對應的元素的name屬性值,而他的value里則是驗證錯誤的提示信息。簡而言之,rules{}中定義驗證規則的方法。 messages{}中定義錯誤輸出。

上面有一點需要注意的就是  equalTo:"#cpassword",這個鍵值對里的value是元素的ID值(如果注意到#號就應該能察覺到)。

 

通過上面的寫法,你就可以自定義提示信息了。或許你會有疑問了,難道我每次驗證表單的時候都要重新自定義提示信息嗎?當然不是了,你還可以Ctrl C+Ctrl V。這當然是玩笑話。。。不過,接下來的方法二會解決你的疑問。

 

方法二、自定義一份提示信息,然后保存成JS文件。把他作為模板,然后在需要的頁面直接引入就行。我是從網上下載了一份。

(function( factory ) {
    if ( typeof define === "function" && define.amd ) {
        define( ["jquery", "../jquery.validate"], factory );
    } else {
        factory( jQuery );
    }
}(function( $ ) {

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: ZH (Chinese, 中文 (Zhōngwén), 漢語, 漢語)
 */
$.extend($.validator.messages, {
    required: "這是必填字段",
    remote: "請修正此字段",
    email: "請輸入有效的電子郵件地址",
    url: "請輸入有效的網址",
    date: "請輸入有效的日期",
    dateISO: "請輸入有效的日期 (YYYY-MM-DD)",
    number: "請輸入有效的數字",
    digits: "只能輸入數字",
    creditcard: "請輸入有效的信用卡號碼",
    equalTo: "你的輸入不相同",
    extension: "請輸入有效的后綴",
    maxlength: $.validator.format("最多可以輸入 {0} 個字符"),
    minlength: $.validator.format("最少要輸入 {0} 個字符"),
    rangelength: $.validator.format("請輸入長度在 {0} 到 {1} 之間的字符串"),
    range: $.validator.format("請輸入范圍在 {0} 到 {1} 之間的數值"),
    max: $.validator.format("請輸入不大於 {0} 的數值"),
    min: $.validator.format("請輸入不小於 {0} 的數值")
});

}));
messages_zh.js

頁面的代碼和JV1.HTML幾乎是一模一樣,只是多引入了一份JS文件。

<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script src="js/jquery.validate.js"></script>
<script src="js/messages_zh.js"></script> 
<script>
    $().ready(function() {
        $("#registerForm").validate();
    });
</script>

</head>
<body>
    <form id="registerForm" method="get" action="">
        <fieldset>
            <p>
                <label for="cusername">用戶名</label> 
                <input id="cusername" name="username" type="text" required="true" rangelength="[2,10]">
            </p>
            <p>
                <label for="cpassword">密碼</label>
                <input id="cpassword" name="password" type="password" required="true" minlength="6">
            </p>
            <p>
                <label for="cconfirmpassword">確認密碼</label> 
                <input id="cconfirmpassword" name="confirmpassword" type="password" required="true" equalTo="#cpassword">
            </p>
            <p>
                <label for="cemail">郵箱</label> 
                <input id="cemail" name="email" required="true" email="true"> </input>
            </p>
            <p>
                <input type="submit" value="提交">
            </p>
        </fieldset>
    </form>
</body>
</html>
JV2-2.HTML

方法一和方法二並不互斥,兩種方法是可以結合使用的。你可以先用方法二保存一份比較通用的模板,然后再用方法一去按具體情況來自定義提示。

 

以上就是我今天下午學習的收獲了。據說在新版本中,又有了新的寫法,既不需要依賴上面提到的jquery.metadata.js庫,也不需要通過javascript自定義提示信息,而是在標簽里以 data-rule-驗證規則、data-msg-提示信息 這樣的格式來重新定義。躍躍欲試......

下面是官網提供的默認校驗規則。

(1)required:true 必輸字段
(2)remote:"check.php" 使用ajax方法調用check.php驗證輸入值
(3)email:true 必須輸入正確格式的電子郵件
(4)url:true 必須輸入正確格式的網址
(5)date:true 必須輸入正確格式的日期
(6)dateISO:true 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22 只驗證格式,不驗證有效性
(7)number:true 必須輸入合法的數字(負數,小數)
(8)digits:true 必須輸入整數
(9)creditcard: 必須輸入合法的信用卡號
(10)equalTo:"#field" 輸入值必須和#field相同
(11)accept: 輸入擁有合法后綴名的字符串(上傳文件的后綴)
(12)maxlength:5 輸入長度最多是5的字符串(漢字算一個字符)
(13)minlength:10 輸入長度最小是10的字符串(漢字算一個字符)
(14)rangelength:[5,10] 輸入長度必須介於 5 和 10 之間的字符串")(漢字算一個字符)
(15)range:[5,10] 輸入值必須介於 5 和 10 之間
(16)max:5 輸入值不能大於5
(17)min:10 輸入值不能小於10
默認校驗規則

好了,摸摸索索了近兩個小時,我的第一篇隨筆到這也算是完成了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM