使用 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();
});