views:

178

answers:

1

In my Asp.net MVC app, I have a custom validator class V and an (ADO.NET Entities) entity model E.

class V : ValidationAttribute
{    
    public override bool IsValid(object value)
    {
        ...        
        if (hasErrors)
            ErrorMessage = errorMsg;
        ...        
    }    
}
public partial class E //the entity model
{    
    [V]
    public object A {get;set;}    
}

I applied validator V to a custom property P in entity model E. Validator V sets the error message in IsValid.

However, it seems as though an instance of entity model E keeps getting reused over and over again (from an Asp.net MVC view) and every time the validation is performed on E the same validator instance gets used.

Because the validator writes to the ErrorMessage property and you can't write to ErrorMessage property more than once, every validation performed after the initial one causes a crash.

Does anyone know how to solve this?

+1  A: 

Try giving your validator the AttributeUsageAttribute and setting the AllowMultiple property to true.

[AttributeUsageAttribute(AttributeTargets.Property, AllowMultiple = true)]
class V : ValidationAttribute {    
    public override bool IsValid(object value) {
        //...        
        if (hasErrors)
            ErrorMessage = errorMsg;
        //...        
    }    
}
çağdaş