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

轉:http://www.cnblogs.com/linzheng/archive/2010/10/14/1851781.htmljavascript

HTML頭部引用:html

<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>java

HTML內容(部分):jquery

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

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();}」,這樣是獲取不到值的。htm

相關文章
相關標籤/搜索