【问题标题】:jQuery validation not working 100% correctlyjQuery 验证不能 100% 正确工作
【发布时间】:2015-08-09 14:48:14
【问题描述】:

我有一个简单的联系表格、电子邮件、名字和姓氏、主题和消息。我已经设置了标准的 MVC 5 验证,并且它有点工作(如果有区别,我将使用 jQuery ajax 提交表单)。如果我将表单留空并单击 Send 则我会收到所有正确的验证消息,但是如果我在列表中填写 1 02 2 项并单击 Send 它实际上发送邮件,缺少 1/2 的信息。

我可以展示你想看到的任何代码,但现在我将从视图、jQuery 和电子邮件视图模型开始。

ContactEmail.cs

using AccessorizeForLess.ViewModels;
using Postal;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace AccessorizeForLess.Models
{
    public class ContactEmail : Email
    {
        public string To { get; set; }

        [DataType(DataType.EmailAddress)]
        [DisplayName("Email Address")]
        [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$", ErrorMessage = "Please enter a valid email address!")]
        [Required(ErrorMessage="Please provide your email address")]
        public string From { get; set; }

        [DisplayName("First Name")]
        [Required(ErrorMessage="Please provide your first name")]
        public string FirstName { get; set; }

        [DisplayName("Last Name")]
        [Required(ErrorMessage="Please provide your last name")]
        public string LastName { get; set; }

        [DisplayName("Subject")]
        [Required(ErrorMessage="Please select a subject")]
        public string SelectedSubject { get; set; }

        [DisplayName("Message")]
        [DataType(DataType.MultilineText)]
        [Required(ErrorMessage="Please provide a message for the email")]
        public string Message { get; set; }

        public List<EmailSubjectViewModel> Subjects { get; set; }
    }
}

我的看法:

@model AccessorizeForLess.Models.ContactEmail
@{
    ViewBag.Title = "Contact";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Contact</h2>
@using (Html.BeginForm("SendAJAX", "Contact", FormMethod.Post, new { @id = "sendContactForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>
            AccessorizeForLess.net&nbsp;&nbsp;&nbsp;
            <a href="https://www.facebook.com/accessorize5orless" target="_blank" title="Accessorize For Less On Facebook"><img src="~/Content/icon-facebook.png" /></a>
        </h4>
        <div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
        <div style="color:red" id="MessageSent"></div>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.From, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.From, new { @id = "from" })
                @Html.ValidationMessageFor(model => model.From)
            </div>
        </div>

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

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

        <div class="form-group">
            @Html.LabelFor(model => model.SelectedSubject, "Category", new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.SelectedSubject, new SelectList(Model.Subjects, "Id", "Subject"), "- Please Select -")
                @Html.ValidationMessageFor(model => model.SelectedSubject)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Message, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Message, new { @cols = "25", @rows = "55" })
                @Html.ValidationMessageFor(model => model.Message)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Send" class="btn btn-default" id="SendMessage" />
            </div>
        </div>
    </div>
}

我的 jQuery:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#sendContactForm").submit(function (e) {
                //alert("Clicked!");
                //prevent Default functionality
                e.preventDefault();

                $("#SendMessage").attr("disbled", true);
                $("#SendMessage").prop("value", "Sending...");
                $("#sending").css("display", "block");
                $("#MessagdSent").html("&nbsp;");

                //get the action-url of the form
                var $form = $(e.target),
                    formData = new FormData(),
                    params = $form.serializeArray()

                $.each(params, function (i, val) {
                    formData.append(val.name, val.value);
                });

                //do your own request an handle the results
                $.ajax({
                    url: $form.attr('action'),
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function (result) {
                        successfulSend(result);
                        resetForm($form)
                    },
                    error: function (result) {
                        failedSend(result);
                    }
                });

                function resetForm(form) {
                    form.find('input:text, input:password, input:file, select, textarea').val('');
                }

                //function that is called when the message is successfully sent
                function successfulSend(result) {
                    //enable the send button
                    $("#SendMessage").attr("disbled", false);

                    //hide the sending gif
                    $("#sending").css("display", "none");

                    //change the text on the button back to Send
                    $("#SendMessage").prop("value", "Send");

                    //set focus to the from email address textbox
                    $("#From").focus();

                    $("#MessageSent").html(result.Message);
                }

                //call this function if for some reason the send fails
                function failedSend(result) {
                    $("#SendMessage").attr("disbled", false);
                    $("#sending").css("display", "none");
                    $("#SendMessage").prop("value", "Send");
                    $("#MessageSent").text(result.ErrorMessage);
                }
            });
        });
    </script>
}

有人可以帮我弄清楚为什么在提供所有必需信息之前它不会继续验证吗?

【问题讨论】:

  • jquery 不显眼的验证在您提交表单时起作用,但您没有提交它(您通过 ajax 发布它并实际上取消了 .submit() 事件)所以验证器 .validate() 函数没有被调用(如果表单无效,这反过来会取消提交事件)
  • 但它正在验证,它验证一个空表单,但只要我在一个条目中输入数据,它就会让它过去
  • 因为您使用 ajax 发布表单(您取消了正常的提交操作)。您可以随时测试表单是否有效,如果无效,只需取消 ajax 调用。
  • 旁注:您可以只使用var formdata = new FormData($('form').get(0)); 并删除$.each(params, ...

标签: jquery asp.net-mvc-5


【解决方案1】:

我在表单上使用了 .valid() 来检查有效性,它似乎已经解决了这个问题。感谢@StephenMuecke 的建议。我的新 jQuery 看起来像这样

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>

    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript">
         $(function () {
        $("#sendContactForm").submit(function (e) {
            //get the action-url of the form
            var $form = $(e.target),
               formData = new FormData($('form').get(0));

            //prevent Default functionality
            e.preventDefault();
            if ($form.valid()) {
                $("#SendMessage").attr("disbled", true);
                $("#SendMessage").prop("value", "Sending...");
                $("#sending").css("display", "block");
                $("#MessagdSent").html("&nbsp;");

                //do your own request an handle the results
                $.ajax({
                    url: $form.attr('action'),
                    data: formData,
                    cache: false,
                    contentType: false,
                    processData: false,
                    type: 'POST',
                    success: function (result) {
                        successfulSend(result);
                        resetForm($form)
                    },
                    error: function (result) {
                        failedSend(result);
                    }
                });
            }               

            function resetForm(form) {
                form.find('input:text, input:password, input:file, select, textarea').val('');
            }

            //function that is called when the message is successfully sent
            function successfulSend(result) {
                //enable the send button
                $("#SendMessage").attr("disbled", false);

                //hide the sending gif
                $("#sending").css("display", "none");

                //change the text on the button back to Send
                $("#SendMessage").prop("value", "Send");

                //set focus to the from email address textbox
                $("#From").focus();

                $("#MessageSent").html(result.Message);
            }

            //call this function if for some reason the send fails
            function failedSend(result) {
                $("#SendMessage").attr("disbled", false);
                $("#sending").css("display", "none");
                $("#SendMessage").prop("value", "Send");
                $("#MessageSent").text(result.ErrorMessage);
            }
        });
    });
    </script>
}

【讨论】:

    猜你喜欢
    • 2013-02-26
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多