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; }
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some ASP.NET Help?
Search fiverr to find help quickly from experienced ASP.NET developers.