Auk
Auk

Reputation: 117

FluentValidation + MVC Extensions (metadata) won't work together

for my project i use two libraries:

  1. FluentValidation (http://fluentvalidation.codeplex.com/) for view model validation
  2. MVC Extensions (http://mvcextensions.codeplex.com/) to fluently configure metadata for my view models

Here is how i configure them (this is done in container builder class):

    /* Model Metadata Registration */
    IEnumerable<IModelMetadataConfiguration> configurations = container.Resolve<IEnumerable<IModelMetadataConfiguration>>();

    IModelMetadataRegistry registry = new ModelMetadataRegistry();

    configurations.Each(configuration => registry.RegisterModelProperties(configuration.ModelType, configuration.Configurations));

    ModelMetadataProviders.Current = new ExtendedModelMetadataProvider(registry);

    /* Fluent Validation Configuration */
    FluentValidationModelValidatorProvider.Configure(x =>
    {
        x.ValidatorFactory = container.Resolve<IValidatorFactory>();
        x.AddImplicitRequiredValidator = false;
    })

Now when i run the application, model will not be validated by FluentValidationModelValidatorProvider. Instead the default mechanism is used. Therefore i had to comment out FluentValidationModelValidatorProvider configuration and use this approach instead:

    IValidator validator = _validatorFactory.GetValidator(typeof(RegisterUserCommand));
    ValidationResult result = validator.Validate(command);

and then:

        if (!result.IsValid)
        {
            command.Password = String.Empty;
            command.ConfirmPassword = String.Empty;

            ModelState.Clear();

            ModelState.AddModelErrors(result.Errors);

            return View(command);
        }

But there must be a way to make them work together. Any advice?

Upvotes: 2

Views: 743

Answers (1)

Khalid Abuhakmeh
Khalid Abuhakmeh

Reputation: 10839

I use FluentValidation and it works fine. I have the following called at App_Start.

public static void Start()
{
    var factory = new DependencyResolverValidatorFactory();
    var provider = new FluentValidationModelValidatorProvider(factory);

    // add remote capabilities
    FluentValidationModelValidationFactory validationFactory = (metadata, context, rule, validator) => new RemoteFluentValidationPropertyValidator(metadata, context, rule, validator);
    provider.Add(typeof(RemoteValidator), validationFactory);

    ModelValidatorProviders.Providers.Add(provider);
    DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
}

Upvotes: 0

Related Questions