Jerad Rose
Jerad Rose

Reputation: 15513

Disable default DataAnnotations unobtrusive validation when using Fluent Validation

I am using Fluent Validation for server-side and unobtrusive client-side validation in MVC. I have had to extend it to suit business needs, and am running into issues with the default DataAnnotations validation. So I just want to completely disable the built-in DataAnnotations provider, and use my own Fluent Validation extensions for doing this validation.

Basically, I need to stop the rendering of the built-in unobtrusive data-val- attributes for value types, such as numbers and dates (data-val-number, data-val-date, data-val-required).

I've tried:

ModelValidatorProviders.Providers.Clear();

And that seems to get rid of the number/date attributes, but required attributes are still there.

I tried:

DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

But that doesn't seem to do anything. Maybe I have it in the wrong location/order?

Upvotes: 1

Views: 2366

Answers (1)

Jerad Rose
Jerad Rose

Reputation: 15513

With Fluent Validation, it has its own flag for disabling required attributes, which has to be configured using FluentValidationModelValidatorProvider. The following code will take care of both the default type attributes as well as required attributes:

//Don't use built-in type attributes (data-val-number, data-val-date)
ModelValidatorProviders.Providers.Clear();

FluentValidationModelValidatorProvider.Configure(
    provider =>
    {
        provider.ValidatorFactory = new UnityValidatorFactory(container);

        //Don't use built-in data-val-required
        provider.AddImplicitRequiredValidator = false;
    }
);

Upvotes: 2

Related Questions