简体   繁体   中英

use attribute validation on multiple checkbox in asp.net mvc application

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.

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM