Thursday, May 7, 2015

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:


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:
<style type="text/css">
    .field-validation-error {
        color: #ff0000;
        display: block;
    }
</style>
 
<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>
  
CONTROLLER:

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");
        }
    }
}
 .................................................................................................................................................................


 The other approach is to create 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 so:
[MustBeTrue(ErrorMessage = "You gotta tick the box!")]
public bool TermsAndConditions { get; set; }


2 comments:

how to validate checkboxlist? kindly help me. thanks in advanced. my email is soni7431@gmail.com

how to use data annotation of multiple checkbox? my code look like,

@Html.Label("Languages")
for (int i = 0; i < Model.languages.Count(); i++)
{
@Html.CheckBoxFor(model => model.languages[i].IsChecked)
@Model.languages[i].Text
@Html.HiddenFor(model => model.languages[i].Text)@Html.HiddenFor(model => model.languages[i].Value)

} in a view and model look like,

public List languages { get; set; }

public class LanguageList
{
public Int64 Value { get; set; }
public string Text { get; set; }

public bool IsChecked { get; set; }

}

and passing values from controller to view? so how to validate?

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More