Fanda
Fanda

Reputation: 3786

How to configure PropertyNameResolver in FluentValidation.AspNetCore 11.2

How can I configure custom PropertyNameResolver after upgrading to FluentValidation.AspNetCore 11.2?

Using version 10.3 I was using this to convert property names in validation response:

.AddFluentValidation(fv =>
{
    // configure validation errors property names to camel case
    fv.ValidatorOptions.PropertyNameResolver = (a, b, c) =>
    {
        return b.Name.ToLowerFirstCharInvariant();
    };
}

Now I have upgraded FluentValidation.AspNetCore to 11.2 and can't find the way how to do similar configuration. None of the following works as expected.

// First try
ValidatorOptions.Global.PropertyNameResolver = (a, b, c) => b.Name.ToLowerFirstCharInvariant();

// Second try
services.Configure<ValidatorConfiguration>(config =>
    config.PropertyNameResolver = (a, b, c) => b.Name.ToLowerFirstCharInvariant()
);

// Also not working with DisplayNameResolver

Upvotes: 0

Views: 916

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11621

It seems that services.AddFluentValidation() should be replaced with services.AddFluentValidationAutoValidation().AddFluentValidationClientsideAdapters();

enter image description here

and there's a static class named ValidatorOptions could be used to pass your configrations and you don't have to configure ValidatorOptions with lambda when you regist the services

enter image description here

I just tried as the document in MVC project:

packages:

enter image description here

In controller:

[HttpPost]
        
        public async Task<IActionResult> Create( Person person)
        {
            ValidationResult result = await _validator.ValidateAsync(person);
            ModelState.Clear();
            if (!result.IsValid)
            {
                // Copy the validation results into ModelState.
                // ASP.NET uses the ModelState collection to populate 
                // error messages in the View.
                result.AddToModelState(this.ModelState);

                // re-render the view when validation failed.
                return View("Create", person);
            }




            return RedirectToAction("Index");
        }

in startup:

public void ConfigureServices(IServiceCollection services)
        {

    services.AddScoped<IValidator<Person>, PersonValidator>();

    .....
    //there's no ToLowerFirstCharInvariant() method by default, so I tried with ToLowerInvariant instead
 
    ValidatorOptions.Global.PropertyNameResolver = (a, b, c) => b.Name.ToLowerInvariant();
    }

The Result:

enter image description here

enter image description here

Upvotes: 1

Related Questions