简体   繁体   English

ASP.NET MVC客户端验证不起作用?

[英]asp.net mvc client side validation not working?

For some reason my client side validation does not seem to be working: 由于某些原因,我的客户端验证似乎无法正常工作:

Here is my html: 这是我的html:

@using (Html.BeginForm("Create", "Home", FormMethod.Post))
{

<hr />

@Html.ValidationSummary(true)
<hr />

<p>
    <label>Select Client_ID: </label>
    <span class="field">
        <select name="clientId" id="clientId">
            @foreach (var item in Model.ClientId)
            {
                <option value="@item">@item</option>
            }
        </select>
    </span>
</p>

<p>
    <label>@Html.LabelFor(model => model.UserModel.name)</label>
    <span class="field">
        @Html.EditorFor(model => model.UserModel.name)
    </span>
    @Html.ValidationMessageFor(model => model.UserModel.name)

</p>

<p>
    <label>@Html.LabelFor(model => model.UserModel.password)</label>
    <span class="field">
        @*<input name="password" id="password" type="password" />*@
        @Html.EditorFor(model => model.UserModel.password)
    </span>
    @Html.ValidationMessageFor(model => model.UserModel.password)
</p>

<p>
    <label>@Html.LabelFor(model => model.UserModel.email)</label>
    <span class="field">
        @*<input name="email" id="email" type="email" />*@
        @Html.EditorFor(model => model.UserModel.email)
    </span>
    @Html.ValidationMessageFor(model => model.UserModel.email)
</p>

<p>
    <label>Select: </label>
    <span class="field">
        <select name="accessLevel" id="accessLevel">
            <option value="3">Company</option>
            <option value="5">End-User</option>
        </select>
    </span>
</p>

<input type="submit" value="Submit" />

Here is my model: 这是我的模型:

 public class CreateUserModel
{
    [Required]
    [Display(Name = "Client_ID")]
    public string clientId { get; set; }

    [Required(ErrorMessage = "A name is required")]
    [MaxLength(20), MinLength(2, ErrorMessage = "Name must be 2 character or more")]
    [Display(Name = "Name")]
    public string name { get; set; }


    [Display(Name = "Email Address")]
    [Required(ErrorMessage = "Email is Required")]
    [RegularExpression(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                        @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                        @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
                        ErrorMessage = "Email is not valid")]
    public string email { get; set; }

    [Required]
    [MaxLength(20), MinLength(6, ErrorMessage = "Password Must be 6 or more chataters long")]
    [Display(Name = "Password")]
    public string password { get; set; }

    [Required]
    public int accessLevel { get; set; }
}

and I do have client side enabled in the webconfig: 而且我确实在webconfig中启用了客户端:

 <appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

{EDIT} added rendered html {EDIT}添加了呈现的html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home Page - My ASP.NET Application</title>
<link href="/Content/bootstrap.css" rel="stylesheet"/>
<link href="/Content/site.css" rel="stylesheet"/>

<script src="/Scripts/modernizr-2.6.2.js"></script>

</head>
<body>
<script src="/Scripts/jquery.validate.js"></script>
<div class="jumbotron">
<h1>Add Users to the website</h1>
</div>
<form action="/Home/Create" method="post">    <hr />
<hr />

<p>
    <label for="UserModel_name">Name</label>
    <span class="field">
        <input type="text" name="name" />
    </span>
    <span class="field-validation-valid" data-valmsg-for="UserModel.name" data-valmsg-replace="true"></span>

</p>
<p>
    <label for="UserModel_password">Password</label>
    <span class="field">
        <input name="password" id="password" type="password" />
    </span>
    <span class="field-validation-valid" data-valmsg-for="UserModel.password" data-valmsg-replace="true"></span>
</p>
<p>
    <label for="UserModel_email">Email Address</label>
    <span class="field">
        <input name="email" id="email" type="email" />
    </span>
    <span class="field-validation-valid" data-valmsg-for="UserModel.email" data-valmsg-replace="true"></span>
</p>
<p>
    <label>Select: </label>
    <span class="field">
        <select name="accessLevel" id="accessLevel">
            <option value="3">Company</option>
            <option value="5">End-User</option>
        </select>
    </span>
</p>
<input type="submit" value="Submit" />
 </form>
    <hr />
    <footer>
        <p>&copy; 2014 - My ASP.NET Application</p>
    </footer>
</div>

<script src="/Scripts/jquery-2.1.0.js"></script>

<script src="/Scripts/bootstrap.js"></script>

For some reason the Html helpers does not have generated validation attributes in the inputs (data-val="true" and the others), check that. 由于某些原因,HTML帮助器在输入中没有生成验证属性(data-val =“ true”等),请进行检查。 Besides to check the order in which the javascript libraries are loaded: 除了检查javascript库的加载顺序外:

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

Your problem is likely that you have jQuery at the bottom of your file, but you are putting jquery.validate at the top. 您的问题可能是文件底部有jQuery,但您将jquery.validate置于顶部。 jQuery has to come before jQuery.validate. jQuery必须先于jQuery.validate。 I would suggest always putting jQuery in your header, not in the body, and it should be the first thing after modernizr. 我建议始终将jQuery放在标题中,而不是放在正文中,这应该是modernizr之后的第一件事。

Also, you do know that jQuery 2.x does not work with IE8 ore earlier, right? 另外,您确实知道jQuery 2.x不能更早地与IE8矿石一起使用,对吗?

It seems that your jquery.validate.js is in wrong position. 看来您的jquery.validate.js位置错误。 It must be after main jquery ref. 它必须在主jQuery引用之后。

For MVC 5, it should be as following: 对于MVC 5,应如下所示:

_Layout.cshtml: (bottom of page) _Layout.cshtml :(页面底部)

<body>
...
...
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/jqueryval") <!-- *required for client side validation! -->
@RenderSection("scripts", required: false)
</body>

where ~/bundles/jqueryval is defined in BundleConfig.cs: RegisterBundles() method: 其中~/bundles/jqueryvalBundleConfig.cs中定义:RegisterBundles()方法:

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

Use: 使用:

@Html.EditorFor

Instead of: 代替:

<input>

And of course you need the jquery.validate.* scripts 当然,您需要jquery.validate.*脚本

TRY THIS: Your validation is failing because you have hard-coded this JQuery link version at the bottom of your page, which likely has been updated to a newer version in your Scripts folder: 尝试:验证失败,因为您已在页面底部对此JQuery链接版本进行了硬编码,该版本可能已在Scripts文件夹中更新为新版本:

<script src="/Scripts/jquery-2.1.0.js"></script>

All you need to do is go to "Scripts", see if there is a "jquery-2.1.0.js" file or you updated JQuery to a newer version. 您所需要做的就是转到“脚本”,查看是否有“ jquery-2.1.0.js”文件,或者您已将JQuery更新为较新的版本。 Type in the newer version file name, if found, and retest. 键入较新版本的文件名(如果找到),然后重新测试。 It should work now. 现在应该可以工作了。 As of this June 2017 we are on JQuery version 3.1.1 截至2017年6月,我们正在使用JQuery版本3.1.1

This happened to me and I was pulling my hair out till I realized I had updated JQuery and saw it removed the old version. 这件事发生在我身上,直到我意识到我已经更新了JQuery并看到它删除了旧版本后,我才开始努力。 I bet that's your issue. 我敢打赌,这是你的问题。 In case you are not doing this, I recommend you not follow the View Page templates that stick validation scripts in View Pages and instead create a simple usercontrol or masterpage or layout view page and stuff your JQuery links in there so they are shared universally by all project pages. 如果您不这样做,我建议您不要遵循将验证脚本粘贴在“视图页面”中的“视图页面”模板,而是创建一个简单的usercontrol或masterpage或layout视图页面,并将您的JQuery链接放入其中,以便所有人共享项目页面。 The browser will naturally cache these pages the first time, so even if they aren't used on other pages they are not loaded again. 浏览器自然会在第一次时缓存这些页面,因此即使未在其他页面上使用它们也不会再次加载。

Not sure if this is being loaded dynamically (eg loading a partial view with Ajax). 不确定是否正在动态加载(例如,使用Ajax加载局部视图)。 If so then you need to parse the html with the validator on the success eg Use something like... 如果是这样,那么您需要在成功时使用验证器解析html,例如,使用...

$.validator.unobtrusive.parse(".target");

Eg 例如

 function loadAPartialView(endPoint) {                    
                $.ajax({
                    url: endPoint,
                    type: 'GET',
                    cache: false,
                    success: function (result) {

                        $('.target').html(result);
                        $('.target').show();

                        // IMPORTANT. Next line is required to get the client side validation to run.
                        $.validator.unobtrusive.parse(".target");
                        $(".loadingMessage").hide(); 
                    },
                    error: function (result) {
                           // Error message... 
                           $(".loadingMessage").hide();

                    }
                });
            };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM