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.

Community
  • 1
  • 1
Danny van der Kraan
  • 5,344
  • 6
  • 31
  • 41

2 Answers2

0

I have not tested but I think the solution might be to pass a list of "Members" to the ValidationResult on the IsValid overriden method :

[I took the example of your former question]

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;
    }
}
Community
  • 1
  • 1
polkduran
  • 2,533
  • 24
  • 34
  • Thanks for answering. I tested it for you. 1st of all, I had to edit your code a bit for it to work (which is peer reviewed at the moment). 2nd of all, doesn't work unfortunatly. If I use the Data Annonation on 1 property I only see the errormessage once (and also 1 textbox red which is the problem) and if I annonate all 4 properties I see the errormessage 4 times (which is also not wanted). So basically, no changes. Same result. – Danny van der Kraan Apr 19 '13 at 13:02
  • I fixed the code. And I also tested and it does not work 'for MVC' (see my other answer) – polkduran Apr 19 '13 at 13:46
0

It seems that ValidationResult.MemberNames has not been implement for MVC, see this.

In some situations, you might be tempted to use the second constructor overload of ValidationResult that takes in an IEnumerable of member names. For example, you may decide that you want to display the error message on both fields being compared, so you change the code to this:

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

If you run your code, you will find absolutely no difference. This is because although this overload is present and presumably used elsewhere in the .NET framework, the MVC framework completely ignores ValidationResult.MemberNames.

polkduran
  • 2,533
  • 24
  • 34
  • but [this answer](http://stackoverflow.com/questions/8573232/assign-validationresult-to-specific-field) says it just works.. – techBeginner Apr 19 '13 at 14:47
  • In that answer they use IValidatableObject http://msdn.microsoft.com/fr-fr/library/system.componentmodel.dataannotations.ivalidatableobject.aspx on the model which is not the same as implementing a custom ValidationAttribute http://msdn.microsoft.com/fr-fr/library/system.componentmodel.dataannotations.validationattribute.aspx – polkduran Apr 19 '13 at 14:53
  • Thanks for researching it. So, no solution yet. I'm going a different route, so my real world problem is solved. But could be interesting to see if this can be done in MVC. – Danny van der Kraan Apr 22 '13 at 06:29