Published: October 16 2013
Last updated: March 11 2016

ASP.NET MVC - Required Checkbox with Data Annotations

I just stumbled across this neat way of making a required checkbox using the built in 'Range' data annotation attribute:

[Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
public bool TermsAndConditions { get; set; }


Here it is in action: (See on .NET Fiddle at https://dotnetfiddle.net/JbPh0X)

Update March 11 2016: Updated the code to add client side validation after a few comments pointed out that the default jquery range validator expects numbers and doesn't play nicely with bool parameters (ie. checkboxes).

Here's the fix to the jquery range validator to make it work correctly with required checkboxes, it falls back to the default validator for other input types:

<script>
	// extend range validator method to treat checkboxes differently
	var defaultRangeValidator = $.validator.methods.range;
	$.validator.methods.range = function(value, element, param) {
		if(element.type === 'checkbox') {
			// if it's a checkbox return true if it is checked
			return element.checked;
		} else {
			// otherwise run the default validation function
			return defaultRangeValidator.call(this, value, element, param);
		}
	}
</script>

 

For completeness, here is another approach to make a checkbox required by creating a custom validation attribute:

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

Which is applied to the model class like this:

[MustBeTrue(ErrorMessage = "You gotta tick the box!")]
public bool TermsAndConditions { get; set; }

 


Need Some ASP.NET Help?

Search fiverr for freelance ASP.NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by