1

I want to use fluentvalidation to automatically verify exceptions, but I can’t do this now. If I put the Validator in the same one project, it will work, but if I put it Validator in another library, it will not work。 The following project one

public class TestValidator : AbstractValidator<WeatherForecast>
{
    public TestValidator()
    {
        RuleFor(x => x.Summary).NotEmpty().WithMessage("Username or email are required");
    }

}

The following project two

I said that registration and verification are placed in different projects, which leads to abnormal verification.

services.AddMvc(options =>
    {
        options.Filters.Add(new ExceptionFilter());
    })
    .AddFluentValidation(options =>
    {
        options.RegisterValidatorsFromAssemblyContaining<Startup>();
    });

2 Answers 2

1

You need change your startup to :

 .AddFluentValidation(options =>
{
    options.RegisterValidatorsFromAssemblyContaining<TestValidator>();
});

Test result:

enter image description here

Sign up to request clarification or add additional context in comments.

10 Comments

Thank you for your answer,I want to automatically scan and register all validation classes that implement the IValidator interface and automatically validate。I want to intercept the verification error message and return a custom error message, how can I do it?
You can see this thread may helpful.
You only need to register one of them, the others will be registered by default
thank you ,I want to intercept the verification error message and return a custom error message, how can I do it?
What do you mean? Isn’t your fluentvalidation your custom error message?
|
0

Today this syntax is obsoleate, the new way to achieve this is

  builder.Services.AddFluentValidationAutoValidation();
     builder.Services.AddFluentValidationClientsideAdapters();
     builder.Services.AddValidatorsFromAssembly(typeof(Program).Assembly);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.