MVC4:jQuery Validation Unobtrusive Native 工作不正常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21043184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:24:28  来源:igfitidea点击:

MVC4: jQuery Validation Unobtrusive Native working incorrectly

jqueryasp.net-mvcasp.net-mvc-4jquery-validateunobtrusive-validation

提问by hofnarwillie

My MVC4 web app is built on Umbraco 7. I have installed the following nuget packages:

我的 MVC4 Web 应用程序是基于 Umbraco 7 构建的。我已经安装了以下 nuget 包:

jQuery 1.10.2
jQuery.Validation 1.11.1
jQuery.Validation.Unobtrusive.Native.MVC4 1.1.0.0

The unobtrusive validation is from this website: http://jqueryvalidationunobtrusivenative.azurewebsites.net/Home/GettingStarted

不显眼的验证来自这个网站:http: //jqueryvalidationunobtrusivenative.azurewebsites.net/Home/GettingStarted

My view looks like this:

我的观点是这样的:

<form id="frmContact" method="post" action="@Url.Action("ContactForm", "ContactFormSurface")">
<div>
    <label>Full Name</label>
    @Html.TextBoxFor(m => m.FullName, true)
    @Html.ValidationMessageFor(m => m.FullName, "*")
</div>
<div>
    <label>Company</label>
    @Html.TextBoxFor(m => m.Company, true)
    @Html.ValidationMessageFor(m => m.Company, "*")
</div>
<div>
    <label>Email Address</label>
    @Html.TextBoxFor(m => m.EmailAddress, true)
    @Html.ValidationMessageFor(m => m.EmailAddress, "*")
</div>
<div>
    <label>Message @Html.ValidationMessageFor(m => m.Message, "*")</label>
    @Html.TextAreaFor(m => m.Message, true, 10, 30, new { @class = "input-xl" })
</div>
@Html.ValidationSummary(false, "Please correct the following errors before submitting the message")
<div>
    <button type="submit">Send</button>
</div>
</form>

In the web.config:

在 web.config 中:

    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>

My model:

我的型号:

public class ContactFormViewModel
{
    [Required, Display(Name = "Full Name")]
    public string FullName { get; set; }

    public string Company { get; set; }

    [Required, Display(Name = "Email Address")]
    [RegularExpression(@"^(?!\.)(""([^""\r\]|\[""\r\])*""|([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$", ErrorMessage="Not a valid email address")]
    public string EmailAddress { get; set; }

    [Required]
    [DataType(DataType.MultilineText)]
    public string Message { get; set; }
}

Here's the scripts (which I have confirmed loads correctly in the browser)

这是脚本(我已确认在浏览器中正确加载)

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>

The rendered HTML looks like this (at initial page load):

呈现的 HTML 如下所示(在初始页面加载时):

<form action="/umbraco/Surface/ContactFormSurface/ContactForm" method="post" id="frmContact">
<div>
    <label>Full Name</label>
    <input type="text" value="" name="FullName" id="FullName" data-rule-required="true" data-msg-required="The Full Name field is required." class="input-validation-error">
    <span data-valmsg-replace="false" data-valmsg-for="FullName" class="field-validation-error">*</span>
</div>
<div>
    <label>Company</label>
    <input type="text" value="" name="Company" id="Company">
    <span data-valmsg-replace="false" data-valmsg-for="Company" class="field-validation-valid">*</span>
</div>
<div>
    <label>Email Address</label>
    <input type="text" value="" name="EmailAddress" id="EmailAddress" data-rule-required="true" data-rule-regex="{&quot;pattern&quot;:&quot;^(?!\.)(\&quot;([^\&quot;\r\\]|\\[\&quot;\r\\])*\&quot;|([-a-z0-9!#$%&amp;'*+/=?^_`{|}~]|(?&lt;!\.)\.)*)(?&lt;!\.)@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$&quot;}" data-msg-required="The Email Address field is required." data-msg-regex="Not a valid email address" class="input-validation-error">
    <span data-valmsg-replace="false" data-valmsg-for="EmailAddress" class="field-validation-error">*</span>
</div>
<div>
    <label>Message <span data-valmsg-replace="false" data-valmsg-for="Message" class="field-validation-error">*</span></label>
    <textarea rows="10" name="Message" id="Message" data-rule-required="true" data-msg-required="The Message field is required." cols="30" class="input-validation-error input-xl"></textarea>
</div>
<div data-valmsg-summary="true" class="validation-summary-errors"><span>Please correct the following errors before submitting the message</span>
        <ul>
            <li>The Full Name field is required.</li>
            <li>The Email Address field is required.</li>
            <li>The Message field is required.</li>
        </ul>
    </div>
<div>
    <button type="submit">Send</button>
</div>
</form>

As you might see, the validation text is already at an invalid state at load time (before any keypresses or form submissions). Also, when I submit the empty form it submits back to the server, so client side validation doesn't actually happen. The jQuery validation scripts run, since the company field is not required and is reflected so in the validation message's class attribute ('field-validation-valid')

如您所见,验证文本在加载时(在任何按键或表单提交之前)已经处于无效状态。此外,当我提交空表单时,它会提交回服务器,因此实际上不会发生客户端验证。jQuery 验证脚本运行,因为 company 字段不是必需的,并且反映在验证消息的类属性 ( 'field-validation-valid')

EDIT: Controller code as requested:

编辑:按要求控制器代码:

    public class ContactFormSurfaceController: Umbraco.Web.Mvc.SurfaceController
    {
        [HttpGet]
        public ActionResult ContactForm(ContactFormViewModel model)
        {
            return PartialView("ContactForm", new ContactFormViewModel());
        }
    }

Can anybody help me out here? Thanks in advance.

有人可以帮我吗?提前致谢。

采纳答案by SoonDead

With this new Native Unobtrusive validation, you seem to have to call .validate()on the form manually.

使用这种新的 Native Unobtrusive 验证,您似乎必须.validate()手动调用表单。

From the Date Demo Example:

日期演示示例

$("form").validate({
    submitHandler: function (form) {
        alert("This is a valid form!")
    }
});

Or in simpler examples:

或者在更简单的例子中:

$("form").validate();

I have no experience with this, but since this only uses the jQuery Validation Plugin, the Documentationmight be worth to read.

我没有这方面的经验,但由于这仅使用 jQuery 验证插件,因此文档可能值得一读。

This WORKSwith your generated HTML:

WORKS你生成的HTML:

See these fiddles for reference:

请参阅这些小提琴以供参考:

http://jsfiddle.net/4JE62/

http://jsfiddle.net/4JE62/

http://jsfiddle.net/4JE62/1/

http://jsfiddle.net/4JE62/1/

回答by Grey Wolf

dont use validate(), use valid() instead

不要使用validate(),而是使用valid()

$("#frmId").valid()

Remember to include validate.unobtrusive.js in your page

请记住在您的页面中包含 validate.unobtrusive.js