简体   繁体   English

使用数据注释/非侵入式验证来验证复选框组

[英]Validate checkbox group with data annotations / unobtrusive validation

I have a model that has a group of checkboxes. 我有一个带有一组复选框的模型。 I want to have a validation that fails unless at least one of the checkboxes is checked. 我希望验证失败,除非选中了至少一个复选框。

When I wrote the original model, I had each checkbox as a separate boolean: 当我编写原始模型时,我将每个复选框都作为一个单独的布尔值:

    [DataMember]
    [Display(ResourceType = typeof(ResourceData), Name = "Monday")]        
    public bool Monday { get; set; }

    [DataMember]
    [Display(ResourceType = typeof(ResourceData), Name = "Tuesday")]
    public bool Tuesday { get; set; }

    [DataMember]
    [Display(ResourceType = typeof(ResourceData), Name = "Wednesday")]
    public bool Wednesday { get; set; }

    [DataMember]
    [Display(ResourceType = typeof(ResourceData), Name = "Thursday")]
    public bool Thursday { get; set; }

    [DataMember]
    [Display(ResourceType = typeof(ResourceData), Name = "Friday")]
    public bool Friday { get; set; }

What would be the best way to design the model with a custom validation class that will also work with unobtrusive validation? 用自定义验证类设计模型的最佳方法是什么,该类也可与非侵入式验证一起使用?

Would it be better to somehow create a custom class for each checkbox and have a collection of those on my model with some data annotation? 以某种方式为每个复选框创建一个自定义类,并在我的模型上添加一些带有数据注释的集合会更好吗?

Here is a start for you: Link . 这是您的起点: 链接 You just to create your own custom Data Annotation and add it just as the link suggests. 您只需创建自己的自定义数据注释并按照链接的建议进行添加即可。 Now, regarding your questions, I believe the best course of action would be to use a collection of checkboxes and adding the annotation to that collection, and then checking if at least one is checked as the link does it. 现在,关于您的问题,我认为最好的做法是使用复选框的集合并将注释添加到该集合中,然后检查是否至少检查了一个链接。

Hope this helps! 希望这可以帮助!

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

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