1. 程式人生 > >jquery.validate 外掛使用

jquery.validate 外掛使用

jQuery.validate外掛是一個簡單易用的外掛,主要作用是在表單提交前進行相關輸入專案的有效性 驗證,驗證通過提交表單,否則提示錯誤;但需要特別注意的是,凡是需要採用該外掛驗證的表單項,均需要定義html的name屬性資訊,且和id值的定義一致,才能達到有效性驗證目的

//==================外掛驗證一直不對哈,明顯未通過驗證也不提示錯誤=========================
        //==================注意哈,html元素必須設定name屬性,且值和id的一直,才能有驗證效果哦==========
        $("#detailsForm").validate({
            errorClass: "error",
            validClass: "success",
            errorElement: "span",
            wrapper: "li",
            errorLabelContainer: $("#errrow span"),
            errorContainer: $("#errrow"),
            rules: {
                name: { required: true },
                age: { range: [18, 150], number:true },
                address: { required: true, minlength: 10 },
                country: "required"
            },
            messages: {
                Name: "Please enter name",
                Age: "Please enter valid age",
                Address: "Please enter address (more than 10 chars)",
                Country: "Please select country"
            },
            submitHandler: function (form) {
                $.noop;
            }
        });

驗證樣式:

<style type="text/css">
        .row {
            height: 40px;
            width: 100%;
            position: relative;
            float: left
        }

        label {
            width: 80px;
            padding: 5px
        }

        input {
            width: 120px;
            height: 30px
        }
        span.error {
            color: red
        }
        input.error {
                border: 1px dotted red;
            }

        input.success {
                background: #ccc;
            }
    </style>

js程式碼驗證表單否有效:

//=====================表達有效提交資料=================== 
if ($("#detailsForm").valid())
                {
                    values = { Name: $("#name").val(), Age: $("#age").val(), Address: $("#address").val(), Country: $("#country").val(), Married: $("#married").prop("checked") };
                    editItem = $.extend(editItem, values);
                    submitData(editItem);

                }


var submitData = function (e) {
        var i = $.Deferred();

        updateData = { Name: e.Name, Age: e.Age, Country: e.Country, Address: e.Address, Married: e.Married };
        $.ajax({
            url: '/Grid/UpdateData',
            type: 'put',
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(updateData)
        }
        ).done(function (e) {
            alert('update data successed');
            i.resolve(e);
            $("#detailsDialog").dialog("close");

        }).fail(function (e) {
            alert('update failed!');
        });
        return i.promise();
    };