jQuery验证插件无法验证我的表单

时间:2018-07-19 20:40:21

标签: jquery asp.net asp.net-mvc jquery-validate

我的主要目标是检查用户输入的值,是否存在于数据库中。所以我的验证看起来像:

 $('#addForm').validate({ 
                rules: {
                    SendingName: {
                        required: true,

                        remote: {
                            url: "@Url.Action(MVC.Product.CheckUniqueSendingName())", 
                            type: "get",
                            data: {
                                subscriptionType: function () {
                                    return @Model.SubscriptionType;
                                },
                                 sendingName: function () {
                                     return $("#SendingName").val();
                                }
                                @*subscriptionType: @Model.SubscriptionType,  
                                sendingName: $("#SendingName").val()*@
                            },
                            success: function (data) {
                                if (data.Data) {
                                    $('#addForm').submit();
                                } else {
                                    message: {
                                        SendingName: 'Record  is already in use!'
                                    }
                                }

                            },
                            // for troubleshooting
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                console.log('status: ' + textStatus);
                                console.log('error: ' + errorThrown); 
                            },

                        }
                    }
                },
            });

我的控制器方法:

public virtual JsonResult CheckUniqueSendingName(int subscriptionType, string sendingName)
        {
            var isUnique = _productService.CheckUniqueSendingName(ProductId, subscriptionType, sendingName);
            JsonResult result = new JsonResult();
            if (isUnique)
            {
                result.Data = false;
            }
            else
                result.Data = true;
            return Json(result,JsonRequestBehavior.AllowGet);
        }

我的表单域

<div class="form-group row">
                    @Html.LabelFor(m => m.SendingName, new { @class = "control-label col-md-3" })
                    <div class="col-md-9">
                        @Html.TextBoxFor(m => m.SendingName, new { @class = "form-control"})
                        <div>
                            @Html.ValidationMessageFor(m => m.SendingName, "", new { @class = "text-danger" })
                        </div>
                    </div>
                </div>

所以我只需要验证表单中的一个字段。但是,当我提交表单时,它不会验证我的表单,没有任何错误。提交表单时如何归档验证消息错误?谢谢

更新:生成的html

<div class="card">
    <div class="card-body">
<form action="product/addsendmailinglist" enctype="multipart/form-data" id="addForm" method="post"><input name="__RequestVerificationToken" type="hidden" value="syd_kzSNc5Nl2H5_h4whYNwVgZcYVwxJ2TubrxE47yugkPbJYlj3DpgbUoGzypDLAknc0bNevWaMe65Miu73EAbwwMKEaXcyy5CqrGdsoXz4B7xExxp1CFyJ0YwOugUIry2k0xvhuvVN3Q3ZDi9nvA2" />            <div class="form-horizontal">

                <input data-val="true" data-val-number="The field ProductId must be a number." data-val-required="The ProductId field is required." id="ProductId" name="ProductId" type="hidden" value="1095" />
                <div class="form-group row">
                    <label class="control-label col-md-3" for="EmailFrom">Email From</label>
                    <div class="col-md-9">
                        <input class="form-control" data-val="true" data-val-required="Field is required" id="EmailFrom" name="EmailFrom" type="text" value="test@gmail.com" />
                        <span class="field-validation-valid text-danger" data-valmsg-for="EmailFrom" data-valmsg-replace="true"></span>
                    </div>
                </div>
                <div class="form-group row">
                    <label class="control-label col-md-3" for="SendingName">Sending Name</label>
                    <div class="col-md-9">
                        <input class="form-control" data-bind="value: SendingName" data-rule-sendingNameValidation="true" id="SendingName" name="SendingName" type="text" value="Fit-Zakaz" />
                        <div>
                            <span class="field-validation-valid text-danger" data-valmsg-for="SendingName" data-valmsg-replace="true"></span>
                        </div>
                    </div>
                </div>
 <div class="form-group row">
                    <div class="col-md-offset-2 col-md-9">
                        <input type="button" data-bind="click: submit" value="Save" class="btn btn-primary btn-rounded" />
                        <a class="btn btn-default btn-rounded" href="/product/details?subscriptionType=2&amp;Tab=emailsending">Cancel</a>
                    </div>
                </div>
</form>

1 个答案:

答案 0 :(得分:0)

好的,我尝试

 $(function () {
            jQuery.validator.addMethod("data-rule-checkunique", function (value) {

                var check_result = false;
                jQuery.ajax({
                    type: "GET",
                    url: "@Url.Action(MVC.Product.CheckUniqueSendingName())?subscriptionType=" +@Model.SubscriptionType + "&sendingName=" + $("#SendingName").val(),
                    async: false,
                    data: JSON.stringify({
                        subscriptionType: @Model.SubscriptionType,
                        sendingName: $("#SendingName").val()
                    }),
                    dataType: "json",
                    success: function (return_data) {
                        if (return_data.Data === false) {
                            check_result = false;
                        } else if (return_data.Data) {
                            check_result = true;
                        }
                    }
                });
                return check_result;
            }, "error message");

重要的是异步:false。我不知道这是不是正确的方法,但是显然可以。如果我做错了,我会听你的评论