c# - ASP.NET MVC : Custom Validation by DataAnnotation

标签 c# .net asp.net-mvc asp.net-mvc-3 data-annotations

我有一个具有 4 个字符串类型属性的模型。我知道您可以使用 StringLength 注释来验证单个属性的长度。但是我想验证 4 个属性的组合长度。

使用数据注释执行此操作的 MVC 方法是什么?

我问这个是因为我是 MVC 的新手,想在制定自己的解决方案之前以正确的方式进行操作。

最佳答案

您可以编写自定义验证属性:

public class CombinedMinLengthAttribute: ValidationAttribute
{
    public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
    {
        this.PropertyNames = propertyNames;
        this.MinLength = minLength;
    }

    public string[] PropertyNames { get; private set; }
    public int MinLength { get; private set; }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
        var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
        var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
        if (totalLength < this.MinLength)
        {
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
        }
        return null;
    }
}

然后你可能有一个 View 模型并用它装饰它的一个属性:

public class MyViewModel
{
    [CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
    public string Foo { get; set; }
    public string Bar { get; set; }
    public string Baz { get; set; }
}

关于c# - ASP.NET MVC : Custom Validation by DataAnnotation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16100300/

相关文章:

asp.net-mvc - 使用 catchall 通配符重定向到 Controller (但使用不同的主 Controller )

c# - ReSharper 并删除多余的括号。 C# 中的 OR 与 AND 逻辑

c# - Razor - 在 foreach 循环中设置复选框的 ID

c# - 获取最新方法总是重新下载

c# - Windows 8 桌面应用程序中的功能区菜单

c# - 使用 OData 的 Web Api HelpPage 不工作

asp.net-mvc - 防止直接访问 IIS 服务器上的文件

c# - 从 C# 中的参数化构造函数调用无参数构造函数?

c# - Directory.GetDirectories 抛出异常

.net - 是否有一个响应式框架主题可以缓冲直到不需要为止?