You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET中校验Model.IsValid时如何要求至少选中一个复选框

实现方案

方案1:模型实现IValidatableObject接口(推荐,无需额外定义类)

这是ASP.NET Core原生支持的模型校验方式,逻辑集中在模型内维护更方便。注意先将ToDate改为可空DateTime并添加[Required]注解,避免非可空类型默认值导致必填校验失效:

using System.ComponentModel.DataAnnotations;
using System.Reflection;

public class CustomDistricts4Weeks : IValidatableObject
{
    [DisplayName("002")]
    public bool D2 { get; set; }
    [DisplayName("003")]
    public bool D3 { get; set; }
    [DisplayName("004")]
    public bool D4 { get; set; }
    [DisplayName("005")]
    public bool D5 { get; set; }
    [DisplayName("006")]
    public bool D6 { get; set; }
    [DisplayName("007")]
    public bool D7 { get; set; }
    [DisplayName("ARL")]
    public bool DArl { get; set; }
    [DisplayName("BAR")]
    public bool DBar { get; set; }
    [DisplayName("COL")]
    public bool DCol { get; set; }
    [DisplayName("GER")]
    public bool DGer { get; set; }
    [DisplayName("MEM")]
    public bool DMem { get; set; }
    [DisplayName("LAK")]
    public bool DLak { get; set; }
    [DisplayName("MIL")]
    public bool DMil { get; set; }
    [DisplayName("JAIL")]
    public bool DJail { get; set; }
    [DisplayName("JAILEAST")]
    public bool DJailEast { get; set; }
    [DisplayName("SCCC")]
    public bool DSCCC { get; set; }
    [DisplayName("1USD")]
    public bool D1USD { get; set; }
    [DisplayName("2USD")]
    public bool D2USD { get; set; }
            
    [Required(ErrorMessage = "请选择有效日期")]
    [DataType(DataType.Date, ErrorMessage = "Date Only")]
    [DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
    [Display(Name = "To Date")]
    public DateTime? ToDate { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        // 反射获取所有布尔属性,判断是否至少有一个为true,后续新增复选框属性无需修改校验逻辑
        bool hasSelected = this.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => p.PropertyType == typeof(bool))
            .Any(p => (bool)p.GetValue(this));

        if (!hasSelected)
        {
            yield return new ValidationResult("请至少选择一个区域", new[] { nameof(D2) });
        }
    }
}

校验逻辑会在ModelState.IsValid判断时自动执行,不符合规则会自动添加模型错误。

方案2:自定义可复用的类校验属性

如果多个模型都需要「至少一个布尔属性为true」的校验规则,可以封装通用校验属性实现复用:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class AtLeastOneBooleanTrueAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value == null) return false;
        
        return value.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => p.PropertyType == typeof(bool))
            .Any(p => (bool)p.GetValue(value));
    }
}

给模型添加该属性即可生效,其余属性不需要修改:

[AtLeastOneBooleanTrue(ErrorMessage = "请至少选择一个区域")]
public class CustomDistricts4Weeks
{
    // 原有属性保持不变,ToDate仍添加[Required]注解即可
}

内容的提问来源于stack exchange,提问作者Steve Cross

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:27:01