ASP.NET/MVC3 - How do I perform validation on checkboxes and array?
I have this field in my model.
class AddUserModel
{
// ....other fields
[Required(ErrorMessage = "Please select at least one role.")]
public string[] Roles { get; set; }
}
In the view this is being rendered as a list of checkboxes:
<div class="editor-field">
@Html.ValidationMessageFor(model => model.Roles)
<ul c开发者_高级运维lass="list_roles">
@foreach (string role in ViewBag.PossibleRoles)
{
<li><input type="checkbox" name="Roles" value="@role" />@role</li>
}
</ul>
</div>
How do I get the validation error message to fire if none of the checkboxes are clicked? Will I need to write a custom validator?
I suspect you'll have to write a custom validator (which isn't hard, BTW; the biggest challenge would be to include client-side error checking, but even that's not that hard).
Another option might be to try using a listbox instead. In Html those have multiple selection capability. The listbox validator might let you require at least one value (I don't know for sure, as I haven't had reason to use a validated listbox in my MVC app yet).
精彩评论