天天看點

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

轉:http://www.cnblogs.com/linzheng/archive/2010/10/14/1851781.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>

HTML内容(部分):

<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代碼部分:

$(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: {

                required: "請輸入使用者名,3-16個字元(字母、數字、下劃線),注冊後不能更改",

                minlength: "使用者名長度不能小于3個字元",

                maxlength: "使用者名長度不能大于16個字元",

                remote: "使用者名不可用"

        }

    });

});

應注意的地方:

data: {

   username: function() {

   return $("#txtUserName").val();

}

有傳回值,如果直接寫“data: {username: $("#txtUserName").val();}”,這樣是擷取不到值的。

繼續閱讀