0

I'm playing with EL Validation Application Block. When a validation is made using attributes, the validation order is not respected. For example:

public class Boat
{
    [Display(Name="License Plate")]
    [RequiredStringValidator]
    [RangeValidator(1,10)]        
    public String RegistrationNumber
    {
        get;
        set;
    }

When i invoke the following code:

Validator vt = CreateValidator(typeof(Boat), ruleSet);            
ValidationResults results = vt.Validate(instance);

results[0] - Error from StringLengthValidator results[1] - Error from RequiredStringValidator(Custom Validator)

The problem is that the order is not always the same. It happens that RequiredStringValidator error is in 0 index position. It seems that .Net CLR does not guarantee Attributes position when retrieving it using Attributes.GetCustomAttributes, that is how VAB get properties attributes.

In this sample, in case of having 2 errors of the same property the first attribute error should be shown(RequiredStringValidator), but sometimes is StringLengthValidator attribute error that is shown because it stays in the ValidationResults first position.

This happen when using ASP.NET MVC model state.

@Html.TextBoxFor(a => a.RegistrationNumber)
@Html.ValidationMessageFor(a => a.RegistrationNumber)

In case of error the StringLengthValidator message should only appear if RequiredStringValidator validator has a valid result.

Any idea?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
JPP
  • 360
  • 6
  • 22
  • It seems quite odd to me that your `StringLengthValidator` is triggered when the string is null or empty. Isn't that an error? Your problem will be solved when you fix this. – Steven Nov 23 '12 at 11:25
  • I understand what you are saying and I'm aware of that, but focus on the sample that two validators are giving error at the same time. I swicth StringLengthValidator for RangeValidator(1, 10) – JPP Nov 23 '12 at 15:52
  • And why is it a problem? A correct error is shown, isn't it? – Steven Nov 23 '12 at 17:34

1 Answers1

0

Just order the results:

var results = (
    from result in vt.Validate(instance)
    orderby result.Validator.GetType()
    select result)
    .ToArray();
Steven
  • 166,672
  • 24
  • 332
  • 435