简体   繁体   English

在ASP.NET MVC应用程序中的多个复选框上使用属性验证

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

I have a viewmodel like this : 我有一个这样的viewmodel:

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. 我的问题是如何使用System.ComponentModel.DataAnnotations强制至少选中一个复选框。 I was wondering if there was like a required attribute to use on the 2 properties. 我想知道是否有需要在2个属性上使用的属性。

Thanks in advance for your help. 在此先感谢您的帮助。

You can create your own cutom validation as below using jQuery :- 您可以使用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 您可以使用Fluent验证

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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