开发者

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

开发者 https://www.devze.com 2022-12-28 22:21 出处:网络
Using MVC2, I have a simple ViewModel that contains a bool field that is rendered on the view as a checkbox.I would like to validate that the user checked the box.The [Required] attribute on my ViewMo

Using MVC2, I have a simple ViewModel that contains a bool field that is rendered on the view as a checkbox. I would like to validate that the user checked the box. The [Required] attribute on my ViewModel doesn't seem to do the trick. I believe this is because the unchecked checkbox form field is not actually transmitted back during the POST, and therefore the validation doesn't run on it.

Is there a standard way to handle checkbox "required" validation in MVC2? or do I have to write a custom validator for it? I suspect the custom validator won't get executed either for the reason mentioned above. Am I stuck checking for it explicitly in my controller? That seems messy...

Any guidance would be appreciated.

Scott

EDIT FOR CLARITY: As pointed out in comments below, this is a "agree to our terms" type of checkbox, and therefor开发者_StackOverflow中文版e "not checked" is a valid answer, so I'm really looking for an "is checked" validation.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消