Reputation: 1975
I have a viewmodel like this :
public UserViewModel
{
public bool IsBlue { get; set; }
public bool IsRed { get; set; }
}
And an associated razor view like this :
<td>
<label for="IsBlue">
<span>is blue ?</span>
</label>
</td>
<td>
<span>@Html.CheckBoxFor(d => d.IsBlue)</span>
</td>
<td>
<label for="IsRed">
<span>is red ?</span>
</label>
</td>
<td>
<span>@Html.CheckBoxFor(d => d.IsRed)</span>
</td>
I have a problem on the server validation side:
The user can check the first, the second, or both textboxes. My question was how can I use the System.ComponentModel.DataAnnotations to force at least one checkbox to be checked. I was wondering if there was like a required attribute to use on the 2 properties.
Thanks in advance for your help.
Upvotes: 2
Views: 2267
Reputation: 11721
You can create your own cutom validation as below using jQuery :-
$("#form").validate({
rules: {
checkbox: {
required: 'input[type="checkbox"]:checked',
minlength: $('input[type="checkbox"]').length();
}
},
messages: {
checkbox: "Please check at least one checkbox.",
}
});
Upvotes: 2
Reputation: 1950
You may use Fluent Validation
[FluentValidation.Attributes.Validator(typeof(CustomValidator))]
public UserViewModel
{
public bool IsBlue { get; set; }
public bool IsRed { get; set; }
}
public class CustomValidator : AbstractValidator<UserViewModel>
{
public CustomValidator()
{
RuleFor(x => x.IsBlue).NotEqual(false)
.When(t => t.IsRed.Equals(false))
.WithMessage("You need to select one");
}
}
Upvotes: 1