jQuery验证不适用于ASP .Net MVC数据注释

时间:2017-01-14 22:56:52

标签: asp.net-mvc asp.net-mvc-4 data-annotations unobtrusive-validation

我正在开发一个ASP .Net MVC 4 Web应用程序。在这里,我尝试使用jQuery的验证和不引人注意的插件来实现验证。示例代码在下面指定

SignUp模型

public class Signup
{

    [StringLength(256,ErrorMessage ="Name can have maximum of 256 characters.")]
    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(10, ErrorMessage = "User code should have of 10 character.", MinimumLength = 10)]
    public string UserCode { get; set; }

[StringLength(256, ErrorMessage = "Password can have maximum of 256 characters.")]
    [Required]
    public string Password { get; set; }

    [StringLength(256, ErrorMessage = "Confirm Password can have maximum of 256 characters.")]
    [Required]
    public string ConfirmPassword { get; set; }
}

Signup.cshtml

 @using (Html.BeginForm("SubmitSignUp", "Foobbox", Model, FormMethod.Post)) {
    @Html.ValidationSummary()
        <span class="input-group-addon">
            <i class="material-icons">face</i>
        </span>
        @Html.EditorFor(x => x.Name, new { @class="form-control", @placeholder = "Name"})
        @Html.ValidationMessageFor(x => x.Name)                                           
    </div>

    <div class="input-group">
        <span class="input-group-addon ">
            <i class="material-icons">email</i>
        </span>
        @Html.TextBoxFor(x => x.EmailId, new { @class = "form-control", @placeholder = "Email" })
        @Html.ValidationMessageFor(x => x.EmailId)                                           
    </div>
}

<head>标记

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

以上指定的验证是在HTML

中生成数据验证属性

例如:

<input class="text-box single-line" data-val="true" data-val-length="Name can have maximum of 256 characters." data-val-length-max="256" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="">

问题是我无法向用户显示相应的错误消息。有什么我想念的吗?或者我做错了什么?

1 个答案:

答案 0 :(得分:1)

在web.config中启用 ClientValidationEnabled 键。

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