简体   繁体   中英

Validation Application Block - Validation attributes multiple error order

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?

Just order the results:

var results = (
    from result in vt.Validate(instance)
    orderby result.Validator.GetType()
    select result)
    .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM