申込フォームによくある、”個人情報保護方針に同意する” などのチェックボックスのValidationのかけ方を紹介します。
まずModel,View,Controllerには下記のように書きます。
Model
1 2 |
[Range(typeof(bool), "true", "true")] public bool PrivacyPolicyAgreement { get; set; } |
View
1 2 |
<label>@Html.CheckBoxFor(x => Model.PrivacyPolicyAgreement) 個人情報保護方針に同意する </label> @Html.ValidationMessageFor(x => Model.PrivacyPolicyAgreement, "エラー字のメッセージ"")) |
Controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
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"); } } } |
もうひと手間必要です
上記のようにMVCを書けば動きそうに見えますが、実はもう一工夫必要です。このままだと、サーバ側のValidationはちゃんとうごくのですが、クライアント側のValidationがなぜか逆になります。(チェックを付けるとエラー、外すとOK という動き)
そこで下記のようなScriptをViewに入れてあげます。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<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> |
これで正常な動きをします。