ASP.NET MVC - Required Checkbox with Data Annotations

CSharp · Mvc

Model

using System;
using System.ComponentModel.DataAnnotations;

namespace MvcRequiredCheckbox
{
	public class SampleViewModel
	{
		[Display(Name = "Terms and Conditions")]
		[Range(typeof(bool), "true", "true", ErrorMessage = "You gotta tick the box!")]
		public bool TermsAndConditions { get; set; }	
	}
}

View

@model MvcRequiredCheckbox.SampleViewModel

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>ASP.NET MVC - Required Checkbox with Data Annotations</title>
		<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
		<style type="text/css">
			.field-validation-error {
				color: #ff0000;
				display: block;
			}
		</style>
	</head>
	
	<body>
		<div class="container">
			<div class="col-md-6 col-md-offset-3">
				<h1>ASP.NET MVC - Required Checkbox with Data Annotations</h1>
	
				@using (Html.BeginForm())
				{
					<div class="form-group">
						@Html.CheckBoxFor(x => x.TermsAndConditions) 
						@Html.LabelFor(x => x.TermsAndConditions)
						@Html.ValidationMessageFor(x => x.TermsAndConditions)
					</div>
				
					<button type="submit" class="btn btn-success submit">Submit</button>
				}
			</div>
		</div>
		<hr />
		<div class="credits text-center">
		  <p>
			  <a href="http://jasonwatmore.com/post/2013/10/16/ASPNET-MVC-Required-Checkbox-with-Data-Annotations.aspx">ASP.NET MVC - Required Checkbox with Data Annotations</a>
		  </p>
		  <p>
			<a href="http://jasonwatmore.com">JasonWatmore.com</a>
		  </p>
		</div>

		<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
		<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
		<script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>
		
		<script>
			// extend jquery range validator to work for required checkboxes
			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>
	</body>
</html>

Controller

using System;
using System.Web.Mvc;
using System.Collections.Generic;

namespace MvcRequiredCheckbox
{
	public class HomeController : Controller
	{
		public ActionResult Index()
		{
			return View();
		}

		[HttpPost]
		public ActionResult Index(SampleViewModel viewModel)
		{
			if(!ModelState.IsValid)
			{
				return View(viewModel);
			}
			
			return Content("Success");
		}
	}
}
;