如何验证jQuery Ajax中的序列化表单?

时间:2015-02-26 14:58:22

标签: javascript jquery ajax asp.net-mvc jquery-ui

我已经创建了一个表单,我将它序列化并将其发送到我的MVC Action方法............我的jQuery Ajax脚本看起来像这样........

$('#submit').click(function () {

    var jsonObj = $('#form').serialize();
    alert(jsonObj);

    $.ajax({
        type: "POST",
        url: '../Doctor/AddDoctor',
        data: JSON.stringify({ "doctor": jsonObj }),
        success: function (data) {
            alert(data.Message);    
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Error: " + errorThrown + " , Please try again");
        }
    });
    return false;



});

所以我需要在将它发送到Action方法之前验证这个表单.....我怎么能这样做?............ 我找到了一个代码,但我不确定我需要在哪里插入它....... 这就是代码.......

$('#myform').validate({ // initialize the plugin
    rules: {
        Name: {
            required: true,
            //email: true
        },
        Charges: {
            required: true,
            //minlength: 5
        },
        WardId: {
            required: true,
            //minlength: 5
        },
        PhoneNo: {
            required: true,
            //minlength: 5
        }
    }
});

有人可以告诉我在哪里插入这个,以验证我的表格..........这就是我的MVC表格的样子............... ........

@using (Html.BeginForm("AddDoctor", "Doctor", FormMethod.Post, new { @id = "form" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4></h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @*@Html.LabelFor(model => model.UserId, new { @class = "col-sm-2 control-label" })*@
            <label class="col-sm-2 control-label"> User ID</label>
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.UserId, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.UserId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "col-sm-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Name, new { @class = "form-control", @name = "Name" })
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>        

        <div class="form-group">
            @*@Html.LabelFor(model => model.DoctorSpecialityId, new { @class = "col-sm-2 control-label" })*@
            <label class="col-sm-2 control-label"> Doctor Speciality ID</label>
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.DoctorSpecialityId, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.DoctorSpecialityId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Charges, new { @class = "col-sm-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Charges, new { @class = "form-control", @name = "Charges" })
                @Html.ValidationMessageFor(model => model.Charges)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.WardId, new { @class = "col-sm-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.WardId, new { @class = "form-control", @name = "WardId" })
                @Html.ValidationMessageFor(model => model.WardId)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhoneNo, new { @class = "col-sm-2 control-label" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.PhoneNo, new { @class = "form-control", @name = "PhoneNo" })
                @Html.ValidationMessageFor(model => model.PhoneNo)
            </div>
        </div>        

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" value="Create" class="btn btn-primary" id="submit" />
            </div>
        </div>

2 个答案:

答案 0 :(得分:1)

您应该在发送Ajax请求之前验证表单,以便:

$(document).ready(function() { 
    $('#form').validate({ // initialize the plugin
        rules: {
            // all the rules
        }
    });

    $('#submit').click(function () {
        var $form = $('#form');

        if ($form.valid()) {

            var jsonObj = $form.serialize();
            alert(jsonObj);

            $.ajax({
                type: "POST",
                url: '../Doctor/AddDoctor',
                data: JSON.stringify({ "doctor": jsonObj }),
                success: function (data) {
                    alert(data.Message);    
                },
                error: function (jqXHR, textStatus, errorThrown) {
                     alert("Error: " + errorThrown + " , Please try again");
                }
           });
       } else {
            alert('form is not valid!');
       }
       return false;

    });
}

答案 1 :(得分:1)

尝试将提交点击处理程序更改为:

$('#submit').click(function () {
    e.preventDefault();

    var doctorForm = $('#form');
    $.validator.unobtrusive.parse(doctorForm);
    doctorForm.validate();

    if (doctorForm.valid()) {
        $.ajax({
            type: "POST",
            url: '@Url.Content("~/Doctor/AddDoctor")',
            data: JSON.stringify({ "doctor": jsonObj }),
            success: function (data) {
                alert(data.Message);    
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert("Error: " + errorThrown + " , Please try again");
            }
        });
        return false;
    }
});