Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 therefore "not checked" is a valid answer, so I'm really looking for an "is checked" validation.

like image 946
Scott Mayfield Avatar asked May 04 '10 16:05

Scott Mayfield


2 Answers

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;
    }
}
like image 83
SQueek Avatar answered Sep 22 '22 14:09

SQueek


I usually use:

[RegularExpression("true")]
like image 37
Jokin Avatar answered Sep 19 '22 14:09

Jokin