Preferred method for adding dynamic model validation options in ASP.Net MVC2

Let's say I have a model with a due date

public class PaymentModel
{
    [PaymentDateValid]
    public DateTime PaymentDate { get; set; }
}

      

I have created a custom PaymentDateValid validator derived from the ValidationAttribute. The validator needs to search the database for the latest payment date and confirm that the shipment date is sent after the last payment date.

Suppose there is some kind of repository or service that is used to get the latest due date and that they are available from the container. Client side validation is optional, but would be nice to have.

What's the best way to inject these dynamic validation parameters into the validator? Or is there a better way to do data-driven validation?

+2


a source to share


1 answer


To add validation attributes dynamically at runtime, you need to create a custom ModelValidatorProvider :

public class MyCustomModelValidatorProvider : DataAnnotationsModelValidatorProvider
{
    protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
    {   
        var newAttributes = attributes;

        //or whatever other criteria you need
        if( metadata.PropertyName == "PaymentDate" )
                newAttributes.Add( new PaymentDateValidAttribute() );

        return base.GetValidators(metadata, context, newAttributes);
    }
}

      



Remember to register your Model Authentication Provider via global.asax.

ModelValidatorProviders.Providers.Clear();
ModelValidatorProviders.Providers.Add(new MyCustomModelValidatorProvider());

      

+1


a source