MVC客户端验证的小示例
配置客户端验证的可用性:
<configuration>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
</configuration>
MVC的客户端的验证也利用了实体上的特性标签,如下:
public class Auction
{
[Required]
[StringLength(50,ErrorMessage = "Title cannot be longer than 50 characters")]
public string Title { get; set; }
[Required]
public string Description { get; set; }
[Range(1, 10000,ErrorMessage = "The auction's starting price must be at least 1")]
public decimal StartPrice { get; set; }
public decimal CurrentPrice { get; set; }
public DateTime EndTime { get; set; }
}
被渲染出的View的代码如下:
<h2>Create Auction</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<p>
@Html.LabelFor(model => model.Title)
@Html.EditorFor(model => model.Title)
@Html.ValidationMessageFor(model => model.Title, "*")
</p>
<p>
@Html.LabelFor(model => model.Description)
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description, "*")
</p>
<p>
@Html.LabelFor(model => model.StartPrice)
@Html.EditorFor(model => model.StartPrice)
@Html.ValidationMessageFor(model => model.StartPrice)
</p>
<p>
@Html.LabelFor(model => model.EndTime)
@Html.EditorFor(model => model.EndTime)
@Html.ValidationMessageFor(model => model.EndTime)
</p>
<p>
<input type="submit" value="Create" />
</p>
}
被渲染出的HTML的代码如下:
<form action="/Auctions/Create" method="post" novalidate="novalidate">
<div class="validation-summary-errors" data-valmsg-summary="true">
<ul>
<li>The Description field is required.</li>
<li>The Title field is required.</li>
<li>Auction may not start in the past</li>
</ul>
</div>
<p>
<label for="Title">Title</label>
<input class="input-validation-error"
data-val="true"
data-val-length="Title cannot be longer than 50 characters"
data-val-length-max="50"
data-val-required="The Title field is required."
>
</p>
</form>
我们看见在最后生成的HTML代码中多出了很多属性,这时候我们引入两个js文件:
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"type="text/javascript"</script>
这两文件会中的代码会根据那些多出的这些属性知道:
哪些input是需要验证的
验证的规则是什么
错误信息是什么
出现错误时应该怎样处理
我们称这个验证方式为隐式验证。