我的模型上有一个必需的注释:
[Required(ErrorMessage = "Please choose an option")]
public bool? AnyDebts { get; set; }
Run Code Online (Sandbox Code Playgroud)
我在web.config中启用了客户端验证:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
我在我的布局中引用了jquery脚本:
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-1.4.4.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.6.custom.min.js")" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)
我还需要做些什么才能使客户端验证工作?服务器端验证仍然有效.
编辑:
啊哈!
我发现客户端验证工作正常.
但是,具体来说,我发现模型属性未经过验证,客户端是那些使用自定义属性注释的属性.例如:
[BooleanRequiredToBeTrue(ErrorMessage = "You must agree to the statements listed")]
public bool StatementAgree { get; set; }
Run Code Online (Sandbox Code Playgroud)
属性的代码:
public class BooleanRequiredToBeTrueAttribute: RequiredAttribute
{
public override bool IsValid(object value)
{
return value != null && (bool)value; …Run Code Online (Sandbox Code Playgroud)