0

I have a Model with a couple of properties and I implemented Darin's answer from my previous question: ASP.NET MVC: Custom Validation by DataAnnotation. This enabled me to validate 4 properties at once (because I needed them together not to exceed a certain length).

The problem is, when I Annonate only 1 of the 4 properties with this custom validator, only that textbox's backgroundcolor will turn red when validation failed. When I annonate all 4 properties all 4 textboxes will turn red, but the error message will be displayed 4 times. Which is ugly. So I set @Html.ValidationSummary(false) so the error messages go in the summary, but all 4 error messages will be summarized (which is logical).

How can I make sure the error message will be displayed only once, while having all 4 textboxes turn red?

Thanks in advance for helping this MVC noob. Appreciate it.

4

2 回答 2

0

我没有测试过,但我认为解决方案可能是将“成员”列表传递给ValidationResultIsValid覆盖的方法:

[我以你之前的问题为例]

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)
        {
            List<string> props = this.PropertyNames.ToList();
            props.Add(validationContext.MemberName);
            return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName), props);
        }
        return null;
    }
}
于 2013-04-19T12:43:47.333 回答
0

似乎ValidationResult.MemberNames尚未针对 MVC 实现,请参阅this

在某些情况下,您可能很想使用 ValidationResult 的第二个构造函数重载,它接受成员名称的 IEnumerable。例如,您可能决定要在要比较的两个字段上显示错误消息,因此您将代码更改为:

return new ValidationResult(
    FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName, OtherProperty });

如果你运行你的代码,你会发现完全没有区别。这是因为尽管此重载存在并且可能在 .NET 框架的其他地方使用,但 MVC 框架完全忽略了 ValidationResult.MemberNames。

于 2013-04-19T13:46:03.300 回答