转载自 http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/

Why would you want to have a required checkbox, i.e. a checkbox that user would have to check? Well, a typical example would be that you have some sort of terms associated with submitting a form that the user has to agree to.

You might think that decorating a boolean property on one of your MVC models with a RequiredAttribute, would mean that if you presented that property in your view as a checkbox, that would require the user to click that checkbox before submitting the form. This is not the case however. If you take a look at the implementation of the RequiredAttribute it is actually casting the value to validate into a string and checking the string length. If it can’t cast the value to a string, it will just return true for IsValid.

It is quite easy however to create your own custom validation attribute that you could decorate your boolean property with. The following code checks if the decorated property is a bool, and if so, requires it to have been set to true;

public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value is bool)
return (bool)value;
else
return true;
} public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata,
ControllerContext context)
{
yield return new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "booleanrequired"
};
}
}

Notice the GetClientValidationRules-method above where we specify the error message to display if client-side validation fails, and what the validation type is. The value we provide as the validation type will be rendered as the name of the rule in the HTML element, and will be used further down to tell jQuery how to validate this property.

After creating the new validation attribute, we need to apply it to a boolean property on out model;

[BooleanRequired(ErrorMessage = "You must accept the terms and conditions.")]
[Display(Name = "I accept the terms and conditions")]
public bool TermsAndConditionsAccepted { get; set; }

Next, create a simple view with a form that includes you boolean property;

@model MyModel@using (Html.BeginForm())
{
<fieldset>
<legend>Terms and Conditions</legend>
@Html.ValidationSummary(true, "Please correct the errors and try again.")
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce facilisis ullamcorper consequat. Vestibulum non sapien lectus.
Nullam at quam eu sapien mattis ultrices.
</p>
<ol>
<li>
@Html.CheckBoxFor(m => m.TermsAndConditionsAccepted)
@Html.LabelFor(m => m.TermsAndConditionsAccepted, new { @class = "checkbox" })
@Html.ValidationMessageFor(m => m.TermsAndConditionsAccepted)
</li>
</ol>
<input type="submit" value="Submit" />
</fieldset>
}

Lastly, in order for client-side validation to work, you need to include the following script in your view (or you can just put line 3 in a javascript file that you reference);

<script type="text/javascript">
(function ($) {
$.validator.unobtrusive.adapters.addBool("booleanrequired", "required");
} (jQuery));
</script>

This just registers a new validation adapter for the boolean required attribute, where the first parameter is the adapter name and the second parameter is the name of jQuery validate rule. The adapter name should match the value we specified earlier as the validation type, and the jQuery validation required-rule will require the user to check the checkbox.

That’s it! This will make sure that the checkbox is checked by the user client-side (using jQuery unobtrusive validation*) and that the boolean property is set to true server-side when the form is submitted to the server.

*The ClientValidationEnabled and UnobtrusiveJavaScriptEnabled application settings must be set to true in your web.config for client-side validation to work.

在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)的更多相关文章

  1. ASP.NET Core Web 应用程序系列(二)- 在ASP.NET Core中使用Autofac替换自带DI进行批量依赖注入(MVC当中应用)

    在上一章中主要和大家分享在MVC当中如何使用ASP.NET Core内置的DI进行批量依赖注入,本章将继续和大家分享在ASP.NET Core中如何使用Autofac替换自带DI进行批量依赖注入. P ...

  2. ASP.NET MVC中为DropDownListFor设置选中项的方法

    在MVC中,当涉及到强类型编辑页,如果有select元素,需要根据当前Model的某个属性值,让Select的某项选中.本篇只整理思路,不涉及完整代码. □ 思路 往前台视图传的类型是List< ...

  3. ASP.NET Core 中文文档 第二章 指南(4.1)ASP.NET Core MVC 与 Visual Studio 入门

    原文:Getting started with ASP.NET Core MVC and Visual Studio 作者:Rick Anderson 翻译:娄宇(Lyrics) 校对:刘怡(Alex ...

  4. MVC中发生System.Data.Entity.Validation.DbEntityValidationException验证异常的解决方法

    发生System.Data.Entity.Validation.DbEntityValidationException这个异常的时候,如果没有用特定的异常类去捕捉,是看不到具体信息的. 通常都是用Sy ...

  5. MVC 中@Html.DropDownListFor() 设置选中项 这么不好使 ? [问题点数:40分,结帖人lkf181]

    http://bbs.csdn.net/topics/390867060 由于不知道错误原因在哪 我尽量把代码都贴出来吧:重点是:在 Controller 类里 我给 SelectListItem集合 ...

  6. MVC中导航菜单,选中项的高亮问题。

      这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当前页面的url. 有两种解决思 ...

  7. MVC中导航菜单,选中项的高亮问题。。

    先上图:             这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当 ...

  8. 在ASP.NET MVC中使用Area区域

    在大型的ASP.NET mvc5项目中一般都有许多个功能模块,这些功能模块可以用Area(中文翻译为区域)把它们分离开来,比如:Admin,Customer,Bill.ASP.NET MVC项目中把各 ...

  9. ASP.NET MVC中的Session设置

    最近在ASP.NET MVC项目中碰到这样的情况:在一个controller中设置了Session,但在另一个controller的构造函数中无法获取该Session,会报"System.N ...

随机推荐

  1. PopupWindow+ListView

    1. 获取打到数据 for (int i = 0; i < iocOutMakeMaterialSubmit.data.size(); i++) { dataListPopupWindow.ad ...

  2. [转载]charisma-master 加载慢的原因及解决方法

    [我的总结] 原文中指出的地址有的已经转换,因为版本问题. 所以根据2014年11月获取的charisma-master版本,应做以下更改: 1.charisma-app.css 这个文件中的外链字体 ...

  3. 多线程-NSOperation中使用ASIHttpRequest注意事项

    最近做的iPhone项目中有一如下功能: app在用户许可后将本地Photos的照片上传到服务器,期间用户可以做其他任何操作,等上传成功后弹出一个toast通知用户. 原先的代码结构是: 获取照片的操 ...

  4. mac出现一个白条

    mac出现一个白条,除了finder没有任何程序运行,出现好几次了,怎么解决? 打开finder输中文出现 按esc键

  5. erl0009 - erlang 读取时间瓶颈解决办法

    读取时间erlang提供有两种方式: 1.erlang:now(); 2.os:timestamp(); 以上两种方式由于erlang系统需要保证读取精度,当并发读取的时候会引起加锁.系统频繁读取时间 ...

  6. AIX 第7章 指令记录

    要点: AIX文件系统的访问路径 AIX文件系统目录树 创建AIX文件系统 文件系统的卸载和删除 文件系统的自动挂载 文件系统的容量管理 文件系统的一致性管理 文件系统的卸载失败 文件系统的快照管理 ...

  7. css3 :nth-child 常用用法

    前端的哥们想必都接触过css中一个神奇的玩意,可以轻松选取你想要的标签并给与修改添加样式,是不是很给力,它就是“:nth-child”. 下面我将用几个典型的实例来给大家讲解:nth-child的实际 ...

  8. 基于CentOS与VmwareStation10搭建Oracle11G RAC 64集群环境:4.安装Oracle RAC FAQ-4.4.无法图形化安装Grid Infrastructure

    无法图形化安装: [grid@linuxrac1 grid]$ ./runInstaller Starting Oracle Universal Installer... Checking Temp ...

  9. vs2010 please select a valid location in the repository

    vs2010 please select a valid location in the repository AnkhSvn版本有问题,我后来使用2.1就ok了记录一下

  10. 【进阶——最小费用最大流】hdu 1533 Going Home (费用流)Pacific Northwest 2004

    题意: 给一个n*m的矩阵,其中由k个人和k个房子,给每个人匹配一个不同的房子,要求所有人走过的曼哈顿距离之和最短. 输入: 多组输入数据. 每组输入数据第一行是两个整型n, m,表示矩阵的长和宽. ...