October 16 2013

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; }

 


ASP.NET MVC, jQuery and Web Development Consultant Sydney

Feel free to drop me a line if you're looking for web development or consulting services in Sydney Australia, I also provide remote contracting services for clients outside Sydney.


Sponsored by