Tuesday, 6 March 2012

Checkbox validation with the MVC data annotations

I've been using MVC3 for a new site and require a check box to be true before continuing. e.g. "Accept T & Cs".

The data annotation have the [Required] attribute for other field types, but this is ignored for check boxes.

You can create your own custom validators. Below is an example for a single check box to ensure it is true.

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeTrueAttribute : ValidationAttribute
      public override bool IsValid(object value)
            return value != null && value is bool && (bool)value;

You can then add the attribute to your MVC component model

[Display(Name = "I accept the terms and conditions")]
[MustBeTrue(ErrorMessage = "Please accept terms and conditions before continuing")]
public bool AcceptTerms { get; set; }

This solution was discovered on StackOverflow


Bob MacNeal said...

Nice! Exactly what I needed. Thank you.

Deepak Porwal said...

This is great post and most useful.