【问题标题】:.NET Core - Custom validation attribute message.NET Core - 自定义验证属性消息
【发布时间】:2019-12-24 16:23:08
【问题描述】:

我正在尝试在 .NET Core 中执行自定义验证属性消息。目的是使工作自动化,所以我不使用 ErrorMessage 参数。 我已完成必填,如下所示:

public class RequiredShortAttribute : RequiredAttribute, IClientModelValidator
{
    public RequiredShortAttribute() : base()
    {
        ErrorMessageResourceType = typeof(ErrorResource);
        ErrorMessageResourceName = "RequiredShort";
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val-required", FormatErrorMessage(""));
    }

    bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
} 

但是当我尝试以这种方式创建其他自定义属性时(例如下面的 StringLength),验证不起作用。我应该添加其他内容吗?

public class StringLengthShortAttribute : StringLengthAttribute, IClientModelValidator
{
    public StringLengthShortAttribute(int max) : base(max)
    {
        ErrorMessageResourceType = typeof(ErrorResource);
        ErrorMessageResourceName = "StringLengthShort";
    }

    public void AddValidation(ClientModelValidationContext context)
    {
        MergeAttribute(context.Attributes, "data-val-length", FormatErrorMessage(""));
    }

    bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
    {
        if (attributes.ContainsKey(key))
        {
            return false;
        }
        attributes.Add(key, value);
        return true;
    }
}

【问题讨论】:

    标签: validation .net-core attributes


    【解决方案1】:

    为什么不把验证器写成:

        public class ShortStringLengthShortAttribute : StringLengthAttribute
        {
            public ShortStringLengthShortAttribute(int maximumLength) : base(maximumLength)
            {
            }
    
            protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            {
                ValidationResult validationResult = new StringLengthAttribute(MaximumLength).GetValidationResult(value, validationContext);
                if (validationResult == ValidationResult.Success)
                {
                    return ValidationResult.Success;
                }
    
                return new ValidationResult("Put here the error message you want"); 
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      • 2012-12-12
      相关资源
      最近更新 更多