How would you validate a checkbox in ASP.Net MVC 2?

时光毁灭记忆、已成空白 提交于 2019-11-30 19:57:28

a custom validator is the way to go. I'll post my code which I used to validate that the user accepts the terms ...

public class BooleanRequiredToBeTrueAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        return value != null && (bool)value;
    }
}

I usually use:

[RegularExpression("true")]

If you didn't want to create your own custom validator and still wanted to use existing attributes in the model you could use:

[Range(typeof(bool), "true", "true", ErrorMessage="You must accept the terms and conditions.")]

This ensures that the range of the boolean value is between true and true. However, whilst this method will work, I would still prefer to use a custom validator in this scenario. I just thought i'd mention this as an alternative option.

I too am looking for a way to have the model binder correctly handle check boxes with Boolean values. In the mean time I'm using this in the Actions:

Object.Property = !String.IsNullOrEmpty(Request.Form["NAME"]);

Maybe this will be of some use to you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!