使用 ASP.NET MVC 和数据注释

将以下内容添加到 <appSettings> 中的 Web.config(在 Views 文件夹中):

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

将 jqueryval 包添加到 BundleConfig.cs:

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

将以下内容添加到需要验证的所有页面(或_Layout.cshml):

<!-- Reference to the jqueryval bundle -->
@Scripts.Render("~/bundles/jqueryval")

<!-- jQuery to apply bootstrap validation classes and glyphicons to inputs -->
<script type="text/javascript">
    $.validator.setDefaults({
        highlight: function (element) {
            $(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback'); // red highlighting
            $(element).closest('.form-group').find('.form-control-feedback').removeClass('glyphicon-ok').addClass('glyphicon-remove'); // red cross glyphicon
        },
        unhighlight: function (element) {
            $(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback'); // green highlighting
            $(element).closest('.form-group').find('.form-control-feedback').removeClass('glyphicon-remove').addClass('glyphicon-ok'); // green tick glyphicon
        }
    });
</script>

将数据注释添加到模型中的相关字段:

using System.ComponentModel.DataAnnotations;

[Required(ErrorMessage = "This field is required.")

在视图中,将以下内容添加到需要验证的每个输入:

<!-- Validation messages -->
<div class="text-danger">@Html.ValidationMessageFor(m => m.SomeField)</div>

<!-- Bootstrap feedback span: -->
<span class="glyphicon form-control-feedback"></span>

将以下内容添加到相关的控制器操作以添加服务器端验证:

if (!ModelState.IsValid)
{
    return View(model);
}
else
{
    // continue with action
}

需要验证的示例输入

模型:

[Required(ErrorMessage = "This field is required.")
[StringLength(maximumLength: 10, ErrorMessage = "This field must be 10 characters or less.")]
public string SomeRequiredField { get; set; }

视图:

<div class="form-group has-feedback">
    <div class="col-md-4">
        @Html.LabelFor(m => m.SomeRequiredField, new { @class = "control-label" })
    </div>
    <div class="col-md-8">
        @Html.TextBoxFor(m => m.SomeRequiredField, new { @class = "form-control" })
        <div class="text-danger">@Html.ValidationMessageFor(m => m.SomeRequiredField)</div>
        <span class="glyphicon form-control-feedback"></span>
    </div>
</div>

可选的

添加以下 jQuery 以验证模糊输入以及提交:

$('input').on('blur', function () {
    $(this).valid();
});