MVC 4客户端验证无法正常工作

时间:2022-12-09 13:45:43

Can anyone tell me why client side validation is not working in my MVC 4 application.

任何人都可以告诉我为什么客户端验证不适用于我的MVC 4应用程序。

_layout.schtml

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

In my web.config I have:

在我的web.config中,我有:

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

In my login.cshtml page I have:

在我的login.cshtml页面中,我有:

@using (Html.BeginForm())
{
    <div class="formscontent">

        <ol>
            <li>
                @Html.LabelFor(x => x.AgreementNumber)
                <br />
                @Html.TextBoxFor(x => x.AgreementNumber, new { size = "30" })
                <br />
                @Html.ValidationMessageFor(m => m.AgreementNumber)
                <br />
                <br />
            </li>
            <li>
                @Html.LabelFor(x => x.UserName)
                <br />
                @Html.TextBoxFor(x => x.UserName, new { size = "30" })
                <br />
                @Html.ValidationMessageFor(m => m.UserName)
                <br />
                <br />
            </li>
            <li>
                @Html.LabelFor(x => x.Password)
                <br />
                @Html.PasswordFor(x => x.Password, new { size = "30" })
                <br />
                @Html.ValidationMessageFor(m => m.Password)
                <br />
                <br />
            </li>
        </ol>

    </div>

    <ol>
        <li>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
        </li>
    </ol>

    <br />

    <input class="mainbutton" type="submit" value="@Model.Localisation.TranslateHtmlString("LogonBtn")" /><br />
    <div style="text-align: left; padding: 0 5px 5px 10px;">
        Forgot login-info? clik <a class="link" href="@Url.Action("Index", "Credentials")">here.</a>
    </div>

}

In the bottom of login page:

在登录页面的底部:

@section Scripts {
  @Scripts.Render("~/bundles/jqueryval")
}

JavaScript is enabled in my browser. In the MVC 4 template project from Visual Studio client validation works fine.

我的浏览器启用了JavaScript。在Visual Studio的MVC 4模板项目中,客户端验证工作正常。

Running the application, on login page when viewing page source, I see this rendered:

运行应用程序,在查看页面源时在登录页面上,我看到这呈现:

<label for="AgreementNumber">number</label>
<br />
<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />
<br />
<span class="field-validation-valid" data-valmsg-for="AgreementNumber" data-valmsg-  replace="true"></span>

and in this in the bottom:

在这个底部:

<script src="/BMWebsite/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/BMWebsite/Scripts/jquery.validate.inline.js"></script>
<script src="/BMWebsite/Scripts/jquery.validate.js"></script>
<script src="/BMWebsite/Scripts/jquery.validate.unobtrusive.js"></script>

My model properties are annotated:

我的模型属性已注释:

public class LogonModel : ModelBase
{
    [MyRequired("AgreementNumberRequiredProperty")]
    [MyDisplay("AgreementNumberLabel")]
    public string AgreementNumber { get; set; }

    [MyRequired("UserNameRequiredProperty")]
    [MyDisplay("UserNameLabel")]
    public string UserName { get; set; }

    [MyRequired("PasswordRequiredProperty")]
    [DataType(DataType.Password)]
    [MyDisplay("PasswordLabel")]
    public string Password { get; set; }

    [MyDisplay("RememberMeCheckBox")]
    public bool RememberMe { get; set; }
}

MyRequired is a class derived from the regular RequiredAttribute. The reason is that my error messages are localised by overriding the FormatErrorMessage(string name) method of the RequiredAttribute class. And it works fine - My labels and error messages are localized.

MyRequired是一个派生自常规RequiredAttribute的类。原因是我的错误消息是通过覆盖RequiredAttribute类的FormatErrorMessage(字符串名称)方法来本地化的。它工作正常 - 我的标签和错误消息已本地化。

MyRequired.cs

public class MyRequiredAttribute : RequiredAttribute
{
    private readonly string _errorMessagekey;

    public MyRequiredAttribute(string errorMessage)
    {
        _errorMessagekey = errorMessage;
    }

    public override string FormatErrorMessage(string name)
    {
        var translation = HttpContext.Current.Session["translation"] as LocalisationHelper;

        return translation != null ? translation.Translate(_errorMessagekey) : ErrorMessage;
    }
}

I put a breakpoint in the POST version of my login action method, and it is being hit. The form is posted to server where server side validation happens. Client side validation doesn't happen.

我在我的登录操作方法的POST版本中放了一个断点,它正被击中。表单将发布到服务器端验证发生的服务器。客户端验证不会发生。

What am I missing?

我错过了什么?

Thank you.

谢谢。

19 个解决方案

#1


41  

I had the same problem. It seems that the unobtrusive validation scripts were not loaded (see screenshot at the end). I fixed it by adding at the end of _Layout.cshtml

我有同样的问题。似乎没有加载不显眼的验证脚本(参见最后的截图)。我通过在_Layout.cshtml的末尾添加来修复它

 @Scripts.Render("~/bundles/jqueryval")

The end result:

最终结果:

   @Scripts.Render("~/bundles/jquery")
   @Scripts.Render("~/bundles/jqueryval")
   @RenderSection("scripts", required: false)

Except for my pretty standard CRUD views everything is Visual studio project template defaults.

除了我非常标准的CRUD视图外,一切都是Visual Studio项目模板的默认设置。

Loaded scripts after fixing the problem: MVC 4客户端验证无法正常工作

修复问题后加载的脚本:

#2


13  

Be sure to add this command at the end of every view where you want the validations to be active.

请确保在要使验证处于活动状态的每个视图的末尾添加此命令。

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

#3


9  

In Global.asax.cs, Application_Start() method add:

在Global.asax.cs中,Application_Start()方法添加:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));

#4


7  

There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:

您的输入中没有数据验证属性。确保您已使用服务器端帮助程序(如Html.TextBoxFor)生成它,并且它位于表单内:

@using (Html.BeginForm())
{
    ...
    @Html.TextBoxFor(x => x.AgreementNumber)
}

Also I don't know what the jquery.validate.inline.js script is but if it somehow depends on the jquery.validate.js plugin make sure that it is referenced after it.

另外我不知道jquery.validate.inline.js脚本是什么,但如果它以某种方式依赖于jquery.validate.js插件,请确保它在它之后被引用。

In all cases look at your javascript console in the browser for potential errors or missing scripts.

在所有情况下,请在浏览器中查看您的javascript控制台是否存在潜在错误或缺少脚本。

#5


7  

you may have already solved this, but I had some luck by changing the order of the jqueryval item in the BundleConfig with App_Start. The client-side validation would not work even on a fresh out-of-the-box MVC 4 internet solution. So I changed the default:

您可能已经解决了这个问题,但我通过使用App_Start更改BundleConfig中jqueryval项的顺序获得了一些运气。即使是在新的开箱即用的MVC 4互联网解决方案上,客户端验证也无法正常工作。所以我更改了默认值:

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

to

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/jquery.unobtrusive*"));

and now my client-side validation is working. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)

现在我的客户端验证工作正常。你只是想确保不显眼的文件在最后(所以它不是侵入性的,哈哈:)

#6


7  

I finally solved this issue by including the necessary scripts directly in my .cshtml file, in this order:

我终于通过在我的.cshtml文件中直接包含必要的脚本来解决这个问题,顺序如下:

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

It's a bit off-topic, but I'm continually amazed by how often this sort of thing happens in Web programming, i.e. everything seems to be in place but some obscure tweak turns out to be necessary to get things going. Flimsy, flimsy, flimsy.

这有点偏离主题,但我不断惊讶于这种事情在Web编程中发生的频率,即一切似乎都已到位,但一些模糊的调整结果证明是必要的。脆弱,脆弱,脆弱。

#7


6  

If you use jquery.validate.js and jquery.validate.unobtrusive.js for validating on client side, you should remember that you have to register any validation attribute of any DOM element on your request. Therefor you can use this code:

如果您使用jquery.validate.js和jquery.validate.unobtrusive.js在客户端进行验证,您应该记住,您必须在请求中注册任何DOM元素的任何验证属性。因此,您可以使用此代码:

$.validator.unobtrusive.parse('your main element on layout');

to register all validation attributes. You can call this method on (for example) : $(document).ajaxSuccess() or $(document).ready() to register all of them and your validation can be occurred successfully instead of registering all js files on cshtml files.

注册所有验证属性。您可以在(例如):$(document).ajaxSuccess()或$(document).ready()上调用此方法来注册所有这些方法,并且您的验证可以成功发生,而不是在cshtml文件上注册所有js文件。

#8


3  

The reason that the validation data-* attributes aren't showing in the rendered html for your input could be that there is no form context. The FormContext is created automatically when you create a form using @using(Html.BeginForm(...)) { ... }.

验证data- *属性未在渲染的html中显示输入的原因可能是没有表单上下文。使用@using(Html.BeginForm(...)){...}创建表单时,会自动创建FormContext。

If you use a regular html tag for your form, you won't get client-side validation.

如果您为表单使用常规html标记,则不会获得客户端验证。

#9


3  

I had an issue with validation, the form posts then it validates,

我有验证问题,表单帖子然后验证,

This Doesn't work with jquery cdn

这不适用于jquery cdn

    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

This Works without jquery cdn

这没有jquery cdn

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Hope helps someone.

希望帮助某人。

#10


2  

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

This code worked for me.

这段代码对我有用。

#11


2  

In my case the validation itself was working (I could validate an element and retrieve a correct boolean value), but there was no visual output.

在我的情况下,验证本身是有效的(我可以验证一个元素并检索一个正确的布尔值),但没有视觉输出。

My fault was that I forgot this line @Html.ValidationMessageFor(m => ...)

我的错是我忘了这行@ Html.ValidationMessageFor(m => ...)

The TS has this in his code and got me on the right track, but I put it in here as reference for others.

TS在他的代码中有这个并让我走上了正确的轨道,但我把它作为其他人的参考。

#12


1  

the line below shows you haven't set an DataAttribute like required on AgreementNumber

下面的行显示您没有在AgreementNumber上设置所需的DataAttribute

<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />

you need

你需要

[Required]
public String AgreementNumber{get;set;}

#13


1  

For me this was a lot of searching. Eventually I decided to use NuGet instead of downloading the files myself. I deleted all involved scripts and scriptbundles and got the following packages (latest versions as of now)

对我来说,这是一个很大的搜索。最终我决定使用NuGet而不是自己下载文件。我删除了所有涉及的脚本和scriptbundles并获得了以下软件包(截至目前的最新版本)

  • jQuery (3.1.1)
  • jQuery(3.1.1)
  • jQuery Validation (1.15.1)
  • jQuery验证(1.15.1)
  • Microsoft jQuery Ubobtrusive Ajax (3.2.3)
  • Microsoft jQuery Ubobtrusive Ajax(3.2.3)
  • Microsoft jQuery Unobtrusive Validation (3.2.3)
  • Microsoft jQuery Unobtrusive Validation(3.2.3)

Then I added these bundles to the BundleConfig file:

然后我将这些包添加到BundleConfig文件中:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate.js",
                "~/Scripts/jquery.validate.unobtrusive.js",
                "~/Scripts/jquery.unobtrusive-ajax.js"));

I added this reference to _Layout.cshtml:

我添加了对_Layout.cshtml的引用:

@Scripts.Render("~/bundles/jquery")

And I added this reference to whichever view I needed validation:

我将此参考添加到我需要验证的视图中:

@Scripts.Render("~/bundles/jqueryval")

Now everything worked.

现在一切正常。

Don't forget these things (many people forget them):

不要忘记这些事情(很多人都忘了):

  • Form tags (@using (Html.BeginForm()))
  • 表格标签(@using(Html.BeginForm()))
  • Validation Summary (@Html.ValidationSummary())
  • 验证摘要(@ Html.ValidationSummary())
  • Validation Message on your input (Example: @Html.ValidationMessageFor(model => model.StartDate))
  • 输入上的验证消息(例如:@ Html.ValidationMessageFor(model => model.StartDate))
  • Configuration ()
  • 配置()
  • The order of the files added to the bundle (as stated above)
  • 添加到包中的文件的顺序(如上所述)

#14


0  

Use:

使用:

@Html.EditorFor

@ Html.EditorFor

Instead of:

代替:

@Html.TextBoxFor

@ Html.TextBoxFor

#15


0  

I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.

我创建了这个html

其中novalidate =“novalidate”阻止客户端jQuery执行,当我删除novalidate =“ novalidate“,客户端jQuery已启用并且正在工作。

#16


0  

I'll like to add to this post, that I was experienceing the same issue but in a PartialView.

我想在这篇文章中添加,我在PartialView中遇到了同样的问题。

And I needed to add

我需要补充一下

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

To the partial view, even if already present in the _Layout view.

对于局部视图,即使已存在于_Layout视图中。

References:

参考文献:

#17


0  

My problem was in web.config: UnobtrusiveJavaScriptEnabled was turned off

我的问题出现在web.config中:UnobtrusiveJavaScriptEnabled已关闭

<appSettings>

<的appsettings>

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

<add key="UnobtrusiveJavaScriptEnabled" value="false" />

</appSettings>

I changed to and now works:

我改为现在工作:

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

#18


0  

Im my case I added and id equals to the name automatically generated for VS on the html and in the code I´ve added a line to that case.

在我的情况下,我添加了id,等于在html上为VS自动生成的名称,在代码中我添加了一行代码。

$(function () {
            $.validator.addMethod('latinos', function (value, element) {
                return this.optional(element) || /^[a-záéóóúàèìòùäëïöüñ\s]+$/i.test(value);
            });

            $("#btn").on("click", function () {
                //alert("aa");
                $("#formulario").validate({                    
                    rules:
                    {
                        email: { required: true, email: true, minlength: 8, maxlength: 80 },
                        digitos: { required: true, digits: true, minlength: 2, maxlength: 100 },
                        nombres: { required: true, latinos: true, minlength: 3, maxlength: 50 },
                        NombresUsuario: { required: true, latinos: true, minlength: 3, maxlength: 50 }
                    },
                    messages:
                    {
                        email: {
                            required: 'El campo es requerido', email: 'El formato de email es incorrecto',
                            minlength: 'El mínimo permitido es 8 caracteres', maxlength: 'El máximo permitido son 80 caracteres'
                        },
                        digitos: {
                            required: 'El campo es requerido', digits: 'Sólo se aceptan dígitos',
                            minlength: 'El mínimo permitido es 2 caracteres', maxlength: 'El máximo permitido son 10 caracteres'
                        },
                        nombres: {
                            required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                            minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                        },
                        NombresUsuario: {
                            required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                            minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                        }
                    }
                });
            });

<tr>@*<div class="form-group">     htmlAttributes: new { @class = "control-label col-md-2" }      , @class = "form-control" }*@
                <td>@Html.LabelFor(model => model.NombresUsuario )</td>

                        @*<div class="col-md-10">*@
                <td>
                    @Html.EditorFor(model => model.NombresUsuario, new { htmlAttributes = new { id = "NombresUsuario" } })
                    @Html.ValidationMessageFor(model => model.NombresUsuario, "", new { @class = "text-danger" })
                </td>

#19


-2  

  @section Scripts
 {
<script src="../Scripts/jquery.validate-vsdoc.js"></script>
<script src="../Scripts/jquery.validate.js"></script>
<script src="../Scripts/jquery.validate.min.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.min.js"></script>
}

#1


41  

I had the same problem. It seems that the unobtrusive validation scripts were not loaded (see screenshot at the end). I fixed it by adding at the end of _Layout.cshtml

我有同样的问题。似乎没有加载不显眼的验证脚本(参见最后的截图)。我通过在_Layout.cshtml的末尾添加来修复它

 @Scripts.Render("~/bundles/jqueryval")

The end result:

最终结果:

   @Scripts.Render("~/bundles/jquery")
   @Scripts.Render("~/bundles/jqueryval")
   @RenderSection("scripts", required: false)

Except for my pretty standard CRUD views everything is Visual studio project template defaults.

除了我非常标准的CRUD视图外,一切都是Visual Studio项目模板的默认设置。

Loaded scripts after fixing the problem: MVC 4客户端验证无法正常工作

修复问题后加载的脚本:

#2


13  

Be sure to add this command at the end of every view where you want the validations to be active.

请确保在要使验证处于活动状态的每个视图的末尾添加此命令。

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

#3


9  

In Global.asax.cs, Application_Start() method add:

在Global.asax.cs中,Application_Start()方法添加:

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(MyRequiredAttribute), typeof(RequiredAttributeAdapter));

#4


7  

There are no data-validation attributes on your input. Make sure you have generated it with a server side helper such as Html.TextBoxFor and that it is inside a form:

您的输入中没有数据验证属性。确保您已使用服务器端帮助程序(如Html.TextBoxFor)生成它,并且它位于表单内:

@using (Html.BeginForm())
{
    ...
    @Html.TextBoxFor(x => x.AgreementNumber)
}

Also I don't know what the jquery.validate.inline.js script is but if it somehow depends on the jquery.validate.js plugin make sure that it is referenced after it.

另外我不知道jquery.validate.inline.js脚本是什么,但如果它以某种方式依赖于jquery.validate.js插件,请确保它在它之后被引用。

In all cases look at your javascript console in the browser for potential errors or missing scripts.

在所有情况下,请在浏览器中查看您的javascript控制台是否存在潜在错误或缺少脚本。

#5


7  

you may have already solved this, but I had some luck by changing the order of the jqueryval item in the BundleConfig with App_Start. The client-side validation would not work even on a fresh out-of-the-box MVC 4 internet solution. So I changed the default:

您可能已经解决了这个问题,但我通过使用App_Start更改BundleConfig中jqueryval项的顺序获得了一些运气。即使是在新的开箱即用的MVC 4互联网解决方案上,客户端验证也无法正常工作。所以我更改了默认值:

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.unobtrusive*",
                    "~/Scripts/jquery.validate*"));

to

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*",
                    "~/Scripts/jquery.unobtrusive*"));

and now my client-side validation is working. You just want to make sure the unobtrusive file is at the end (so it's not intrusive, hah :)

现在我的客户端验证工作正常。你只是想确保不显眼的文件在最后(所以它不是侵入性的,哈哈:)

#6


7  

I finally solved this issue by including the necessary scripts directly in my .cshtml file, in this order:

我终于通过在我的.cshtml文件中直接包含必要的脚本来解决这个问题,顺序如下:

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

It's a bit off-topic, but I'm continually amazed by how often this sort of thing happens in Web programming, i.e. everything seems to be in place but some obscure tweak turns out to be necessary to get things going. Flimsy, flimsy, flimsy.

这有点偏离主题,但我不断惊讶于这种事情在Web编程中发生的频率,即一切似乎都已到位,但一些模糊的调整结果证明是必要的。脆弱,脆弱,脆弱。

#7


6  

If you use jquery.validate.js and jquery.validate.unobtrusive.js for validating on client side, you should remember that you have to register any validation attribute of any DOM element on your request. Therefor you can use this code:

如果您使用jquery.validate.js和jquery.validate.unobtrusive.js在客户端进行验证,您应该记住,您必须在请求中注册任何DOM元素的任何验证属性。因此,您可以使用此代码:

$.validator.unobtrusive.parse('your main element on layout');

to register all validation attributes. You can call this method on (for example) : $(document).ajaxSuccess() or $(document).ready() to register all of them and your validation can be occurred successfully instead of registering all js files on cshtml files.

注册所有验证属性。您可以在(例如):$(document).ajaxSuccess()或$(document).ready()上调用此方法来注册所有这些方法,并且您的验证可以成功发生,而不是在cshtml文件上注册所有js文件。

#8


3  

The reason that the validation data-* attributes aren't showing in the rendered html for your input could be that there is no form context. The FormContext is created automatically when you create a form using @using(Html.BeginForm(...)) { ... }.

验证data- *属性未在渲染的html中显示输入的原因可能是没有表单上下文。使用@using(Html.BeginForm(...)){...}创建表单时,会自动创建FormContext。

If you use a regular html tag for your form, you won't get client-side validation.

如果您为表单使用常规html标记,则不会获得客户端验证。

#9


3  

I had an issue with validation, the form posts then it validates,

我有验证问题,表单帖子然后验证,

This Doesn't work with jquery cdn

这不适用于jquery cdn

    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

This Works without jquery cdn

这没有jquery cdn

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Hope helps someone.

希望帮助某人。

#10


2  

<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>

This code worked for me.

这段代码对我有用。

#11


2  

In my case the validation itself was working (I could validate an element and retrieve a correct boolean value), but there was no visual output.

在我的情况下,验证本身是有效的(我可以验证一个元素并检索一个正确的布尔值),但没有视觉输出。

My fault was that I forgot this line @Html.ValidationMessageFor(m => ...)

我的错是我忘了这行@ Html.ValidationMessageFor(m => ...)

The TS has this in his code and got me on the right track, but I put it in here as reference for others.

TS在他的代码中有这个并让我走上了正确的轨道,但我把它作为其他人的参考。

#12


1  

the line below shows you haven't set an DataAttribute like required on AgreementNumber

下面的行显示您没有在AgreementNumber上设置所需的DataAttribute

<input id="AgreementNumber" name="AgreementNumber" size="30" type="text" value="387893" />

you need

你需要

[Required]
public String AgreementNumber{get;set;}

#13


1  

For me this was a lot of searching. Eventually I decided to use NuGet instead of downloading the files myself. I deleted all involved scripts and scriptbundles and got the following packages (latest versions as of now)

对我来说,这是一个很大的搜索。最终我决定使用NuGet而不是自己下载文件。我删除了所有涉及的脚本和scriptbundles并获得了以下软件包(截至目前的最新版本)

  • jQuery (3.1.1)
  • jQuery(3.1.1)
  • jQuery Validation (1.15.1)
  • jQuery验证(1.15.1)
  • Microsoft jQuery Ubobtrusive Ajax (3.2.3)
  • Microsoft jQuery Ubobtrusive Ajax(3.2.3)
  • Microsoft jQuery Unobtrusive Validation (3.2.3)
  • Microsoft jQuery Unobtrusive Validation(3.2.3)

Then I added these bundles to the BundleConfig file:

然后我将这些包添加到BundleConfig文件中:

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate.js",
                "~/Scripts/jquery.validate.unobtrusive.js",
                "~/Scripts/jquery.unobtrusive-ajax.js"));

I added this reference to _Layout.cshtml:

我添加了对_Layout.cshtml的引用:

@Scripts.Render("~/bundles/jquery")

And I added this reference to whichever view I needed validation:

我将此参考添加到我需要验证的视图中:

@Scripts.Render("~/bundles/jqueryval")

Now everything worked.

现在一切正常。

Don't forget these things (many people forget them):

不要忘记这些事情(很多人都忘了):

  • Form tags (@using (Html.BeginForm()))
  • 表格标签(@using(Html.BeginForm()))
  • Validation Summary (@Html.ValidationSummary())
  • 验证摘要(@ Html.ValidationSummary())
  • Validation Message on your input (Example: @Html.ValidationMessageFor(model => model.StartDate))
  • 输入上的验证消息(例如:@ Html.ValidationMessageFor(model => model.StartDate))
  • Configuration ()
  • 配置()
  • The order of the files added to the bundle (as stated above)
  • 添加到包中的文件的顺序(如上所述)

#14


0  

Use:

使用:

@Html.EditorFor

@ Html.EditorFor

Instead of:

代替:

@Html.TextBoxFor

@ Html.TextBoxFor

#15


0  

I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.

我创建了这个html

其中novalidate =“novalidate”阻止客户端jQuery执行,当我删除novalidate =“ novalidate“,客户端jQuery已启用并且正在工作。

#16


0  

I'll like to add to this post, that I was experienceing the same issue but in a PartialView.

我想在这篇文章中添加,我在PartialView中遇到了同样的问题。

And I needed to add

我需要补充一下

<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

To the partial view, even if already present in the _Layout view.

对于局部视图,即使已存在于_Layout视图中。

References:

参考文献:

#17


0  

My problem was in web.config: UnobtrusiveJavaScriptEnabled was turned off

我的问题出现在web.config中:UnobtrusiveJavaScriptEnabled已关闭

<appSettings>

<的appsettings>

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

<add key="UnobtrusiveJavaScriptEnabled" value="false" />

</appSettings>

I changed to and now works:

我改为现在工作:

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

#18


0  

Im my case I added and id equals to the name automatically generated for VS on the html and in the code I´ve added a line to that case.

在我的情况下,我添加了id,等于在html上为VS自动生成的名称,在代码中我添加了一行代码。

$(function () {
            $.validator.addMethod('latinos', function (value, element) {
                return this.optional(element) || /^[a-záéóóúàèìòùäëïöüñ\s]+$/i.test(value);
            });

            $("#btn").on("click", function () {
                //alert("aa");
                $("#formulario").validate({                    
                    rules:
                    {
                        email: { required: true, email: true, minlength: 8, maxlength: 80 },
                        digitos: { required: true, digits: true, minlength: 2, maxlength: 100 },
                        nombres: { required: true, latinos: true, minlength: 3, maxlength: 50 },
                        NombresUsuario: { required: true, latinos: true, minlength: 3, maxlength: 50 }
                    },
                    messages:
                    {
                        email: {
                            required: 'El campo es requerido', email: 'El formato de email es incorrecto',
                            minlength: 'El mínimo permitido es 8 caracteres', maxlength: 'El máximo permitido son 80 caracteres'
                        },
                        digitos: {
                            required: 'El campo es requerido', digits: 'Sólo se aceptan dígitos',
                            minlength: 'El mínimo permitido es 2 caracteres', maxlength: 'El máximo permitido son 10 caracteres'
                        },
                        nombres: {
                            required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                            minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                        },
                        NombresUsuario: {
                            required: 'El campo es requerido', latinos: 'Sólo se aceptan letras',
                            minlength: 'El mínimo permitido es 3 caracteres', maxlength: 'El máximo permitido son 50 caracteres'
                        }
                    }
                });
            });

<tr>@*<div class="form-group">     htmlAttributes: new { @class = "control-label col-md-2" }      , @class = "form-control" }*@
                <td>@Html.LabelFor(model => model.NombresUsuario )</td>

                        @*<div class="col-md-10">*@
                <td>
                    @Html.EditorFor(model => model.NombresUsuario, new { htmlAttributes = new { id = "NombresUsuario" } })
                    @Html.ValidationMessageFor(model => model.NombresUsuario, "", new { @class = "text-danger" })
                </td>

#19


-2  

  @section Scripts
 {
<script src="../Scripts/jquery.validate-vsdoc.js"></script>
<script src="../Scripts/jquery.validate.js"></script>
<script src="../Scripts/jquery.validate.min.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.min.js"></script>
}