asp.net mvc客户端验证不起作用?

时间:2014-02-24 10:59:40

标签: c# asp.net asp.net-mvc jquery-validate unobtrusive-validation

出于某种原因,我的客户端验证似乎不起作用:

这是我的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" />

这是我的模特:

 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; }
}

我确实在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}添加了渲染的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>

6 个答案:

答案 0 :(得分:16)

由于某些原因,Html助手在输入中没有生成验证属性(data-val =&#34; true&#34;以及其他),请检查。除了检查加载javascript库的顺序之外:

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

答案 1 :(得分:10)

您的问题可能是您的文件底部有jQuery,但是您将jquery.validate放在顶部。 jQuery必须在jQuery.validate之前出现。我建议总是把jQuery放在你的标题中,而不是放在正文中,它应该是现代化之后的第一件事。

另外,你知道jQuery 2.x早先不适用于IE8,对吗?

答案 2 :(得分:3)

您的jquery.validate.js似乎处于错误的位置。它必须在主jquery ref。

之后

对于MVC 5,它应该如下:

_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>

其中~/bundles/jqueryval BundleConfig.cs:RegisterBundles()方法中定义:

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

答案 3 :(得分:2)

使用:

@Html.EditorFor

而不是:

<input>

当然,您需要jquery.validate.*脚本

答案 4 :(得分:0)

尝试:您的验证失败,因为您在页面底部对此JQuery链接版本进行了硬编码,该版本可能已更新为Scripts文件夹中的较新版本:

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

您需要做的就是转到“Scripts”,看看是否有“jquery-2.1.0.js”文件,或者您将JQuery更新为更新版本。如果找到,请键入较新的版本文件名,然后重新测试。它现在应该工作。截至2017年6月,我们使用的是JQuery 3.1.1版

这件事发生在我身上,我拉着头发,直到我意识到我已经更新了JQuery并看到它删除了旧版本。我打赌那是你的问题。如果你不这样做,我建议你不要按照查看页面模板粘贴查看页面中的验证脚本,而是创建一个简单的用户控件或母版页或布局视图页面,并在那里填充你的JQuery链接,以便所有人共享它们项目页面。浏览器会自然地第一次缓存这些页面,所以即使它们没有在其他页面上使用,它们也不会再次加载。

答案 5 :(得分:0)

不确定是否正在动态加载(例如,使用Ajax加载部分视图)。如果是这样,那么你需要用成功的验证器解析html,例如 使用像...这样的东西。

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

E.g。

 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();

                    }
                });
            };