2

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.

3
  • 1
    There is nothing out of the box that will do this. You would need to write your own validation Commented Jun 8, 2015 at 9:05
  • In this case, how can I display the error message displayed like in the other validation attribute from my check method Commented Jun 8, 2015 at 9:07
  • Easiest would be in the POST method, if both are false, add a ModelState error - ModelState.AddModelError("", "You must select at least one") and return the view. The error will be displayed in the @Html.ValidationSummary() Commented Jun 8, 2015 at 9:12

2 Answers 2

2

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.",
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.