How to require that a checkbox is selected when submitting a form in ASP.NET MVC

Posted on Wednesday, October 19, 2016 at 4:28 PM into code & csharp by Steve Woods.
Roughly a 1 minute read.

Sometimes you really need a user to put a tick in a checkbox, for instance when submitting a registration form where acceptance of terms and conditions is required.

Here's how you do it in ASP.NET MVC, via a custom ValidationAttribute that decorates a property of your ViewModel:

The Custom ValidationAttribute

public class MustBeTrueAttribute : ValidationAttribute
    public override bool IsValid(object value)
        return value is bool && (bool)value;

Decorating your ViewModel property

[MustBeTrue(ErrorMessage = "Please check the box before continuing!")]
public bool TandCs { get; set; }

Job done :)



Please consider what you post!
Chillax if you're angry.