Required CheckBox validation in ASP.Net MVC 2 onwards


Having forms with checkboxes that require users to check them to be valid is a pretty common phenomenon on the internet today, however when thinking about this in terms of ASP.Net MVC it can not always be obvious what the best approach to take is. Thankfully the ASP.Net MVC team gave us the support to create a really simple solution when they added inheritable validation classes to the framework.

Custom Validation Attributes

image By now if you’ve been using MVC for a while you’ll be more than aware of the way MVC adds validation to a classes properties is by using Data Annotation Attributes.

public string Name { get; set; }

The great thing is in MVC 2 onwards, creating your own validation attributes is just too easy, by inheriting from the ValidationAttribute class.

To use this to our advantage, we’ll create a custom attribute class that inherits from this and checks to see the following:

  • That the property being validated is a Boolean AND
  • That it is true

It sounds simple because it is!

Magic Incantations

Create a new class and call it BooleanMustBeTrueAttribute

Paste the following code into the class

public class BooleanMustBeTrueAttribute : ValidationAttribute 
    public override bool IsValid(object propertyValue)
        return propertyValue != null
            && propertyValue is bool
            && (bool)propertyValue;

Now in the model class that you are looking to validate, decorate your “terms and conditions” or “i am over 18” or what ever other Boolean property that you want to validate with your new attribute.

[BooleanMustBeTrue(ErrorMessage="You must agree to the terms and conditions")]
public bool TermsAndConditions { get; set; }

And that’s it!

As you see from the above example, support for custom validation attributes (like so much of the ASP.Net MVC framework) makes for some pretty elegant looking code.