利用jquery.validate異步驗證用戶名是否存在

參考文獻:http://www.cnblogs.com/Jaylong/archive/2011/04/28/Jquery.htmljavascript

通過上百次的試驗試和搜索,終於把jquery.validate的各類功能用法瞭解清楚,網上關於jquery.validate的AJAX表單驗證比較少,特別是對rules裏面的remote提得比較簡單,使得學習起來比較難,下面發佈一下我我的的用法:html

HTML頭部引用:java

<script type="text/javascript" src="../js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="../js/jquery.validate.min.js"></script> <script type="text/javascript" src="../js/messages_cn.js"></script>jquery

HTML內容(部分):post

<form name="form1" id="form1" method="post" action=""> <dl>   <dt>用戶名:</dt>   <dd><input name="txtUserName" id="txtUserName" type="text" class="input1" /></dd> </dl> </form>學習

JS代碼部分:ui

$(function() { //表單驗證JS     $("#form1").validate({         //出錯時添加的標籤         errorElement: "span",         rules: {             txtUserName: {                 required: true,                 minlength: 3,                 maxlength: 16,                 remote: {                     type: "post",                     url: "/tools/ValidateUserName.ashx",                     data: {                         username: function() {                             return $("#txtUserName").val();                         }                     },                     dataType: "html",                     dataFilter: function(data, type) {                         if (data == "true")                             return true;                         else                             return false;                     }                 }             }         },         success: function(label) {             //正確時的樣式             label.text(" ").addClass("success");         },         messages: {             txtUserName: {                 required: "請輸入用戶名,3-16個字符(字母、數字、下劃線),註冊後不能更改",                 minlength: "用戶名長度不能小於3個字符",                 maxlength: "用戶名長度不能大於16個字符",                 remote: "用戶名不可用"             }         }url

    }); });spa

應注意的地方:orm

data: {    username: function() {    return $("#txtUserName").val(); } 有返回值,若是直接寫「data: {username: $("#txtUserName").val();}」,這樣是獲取不到值的。

相關文章
相關標籤/搜索