【问题标题】:FluentValidation NotNull on enum values枚举值上的 FluentValidation NotNull
【发布时间】:2017-04-26 13:28:30
【问题描述】:

我有一个基于“int”的具有枚举属性的模型。 我需要验证此属性不为空。但是NotEmpty 禁止0 值。而NotNull 只是不起作用,因为枚举属性不能为空。 我不能让我的财产可以为空。 如何进行此类验证?

【问题讨论】:

    标签: fluentvalidation fluentvalidation-2.0


    【解决方案1】:

    只要枚举类型是 int 就可以做到以下几点:

    public class Status
        {
            public StatusType type { get; set; }
        }
    
        public enum StatusType
        {
            open = 1,
            closed = 2
        }
    
        public class StatusValidator : AbstractValidator<Status>
        {
            public StatusValidator()
            {
                RuleFor(x => x.type).Must(x => x != 0);
            }
    
        }
    

    如果您无法避免 0,您可以为模型定义一个解决方法,如下所示(来源Choosing the default value of an Enum type without having to change values):

    [注意:您需要包含using System.ComponentModel;]

    public class Status
    {
        public StatusType type { get; set; }
    }
    
    [DefaultValue(_default)]
    public enum StatusType
    {
        _default = -1,
        test = 0,
        open = 1,
        closed = 2,
    
    }
    
    public static class Utilities
    {
        public static TEnum GetDefaultValue<TEnum>() where TEnum : struct
        {
            Type t = typeof(TEnum);
            DefaultValueAttribute[] attributes = (DefaultValueAttribute[])t.GetCustomAttributes(typeof(DefaultValueAttribute), false);
            if (attributes != null &&
                attributes.Length > 0)
            {
                return (TEnum)attributes[0].Value;
            }
            else
            {
                return default(TEnum);
            }
        }
    }
    
    public class StatusValidator : AbstractValidator<Status>
    {
        public StatusValidator()
        {
            RuleFor(x => x.type).Must(x => x != Utilities.GetDefaultValue<StatusType>());
        }
    
    }
    

    【讨论】:

    • 对不起,我不能。在我的枚举中无法避免 0 值。
    • 谢谢你,乔瓦尼!你的建议很好。但我想保持我的枚举干净,而不是引入一些默认值。相反,在我的模型的构造函数中,我将属性设置为一些无效值(例如-1)并将其转换为枚举。然后IsInEnum 方法就像一个魅力!
    【解决方案2】:

    我想您想在 mvc 控制器中验证模型,但您应该更清楚您的使用上下文。 我认为模型在类型方面应该尽可能宽,以适应用户在 UI 级别做出的任何可能的选择,例如始终使用可为空的类型。当模型绑定尝试构建对象时,它匹配属性名称以请求键/值并将匹配值设置到属性中。当它在请求中找不到任何匹配项时,它会将属性保留为其默认值(在 int 的情况下为 0)。在这种情况下,您必须知道用户是否将该字段留空或故意在其中写入零值的唯一方法是检查模型状态。那么在第一种情况下,将在模型状态中跟踪错误(字段不能为空......等等)并检查模型状态,您可以知道用户是否设置了值。 Fluent 验证在模型绑定之后开始发挥作用,它依赖于模型绑定本身的工作,可怜的他无法真正理解零的真正含义(空值/缺失值或零值)。

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 2022-06-22
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 2010-12-10
      • 2012-08-31
      相关资源
      最近更新 更多