Is there a way to validate bool checkboxes using Data Annotations in C# MVC?
All the examples I have seen for the custom data annotation approach are just validating one checkbox like a Accept Terms box. I need to validate that at least one checkbox has been selected in a List<>
For Example:
public class QuestionOptionViewModel
{
public int? Id { get; set; }
public string Text { get; set; }
public string QuestionType { get; set; }
[RequiredIf("QuestionType", "text", ErrorMessage = "Required Field")]
public string Value { get; set; }
[RequiredIf("QuestionType", "checkbox", ErrorMessage = "Required Field")]
public bool IsChecked { get; set; }
}
I am storing a list of IsChecked. I wanted to know rather one of the Checkboxes in the list was selected using Data Annotations.
ViewModel
public class VisitorAgreementTermViewModel
{
[Required]
[Display(Name = "Message Accept.")]
//[Range(typeof(bool), "true", "true", ErrorMessage = "Error Message Text.")]
[RegularExpression("True", ErrorMessage = "Error Message Text.")]
public bool Agreement { get; set; }
}
View
@using (Ajax.BeginForm("AgreementTerms", "Visitors", new AjaxOptions()
{
HttpMethod = "POST",
UpdateTargetId = "document-body",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "document-loading",
OnBegin = "ClearBody('document-body')"
}))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="form-group m-b-xl col-md-offset-1">
<label class="checkbox-inline">
@Html.CheckBoxFor(model => model.Agreement)
@Html.LabelFor(model => model.Agreement)
<br />
@Html.ValidationMessageFor(model => model.Agreement, "", new { @class = "text-danger" })
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
</label>
</div>
<div class="col-sm-2 col-sm-offset-9">
<button type="submit" class="btn btn-success"><span class="fa fa-fw fa-arrow-right"></span> Continue</button>
</div>
</div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AgreementTerms(AgreementTermViewModel aterms)
{
if (ModelState.IsValid)
return PartialView("_PreRegistration");
return PartialView("_AgreementTerms", aterms);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.