1

I need to validate PinCode send from UI, this value need to check with database if not null. I have this code to validate using Fluent Validations:

public class PinCodeValidator : AbstractValidator<string?>
{
    public PinCodeValidator()
    {
        When(r => !string.IsNullOrEmpty(r), () =>
        {
            RuleFor(x => x)
               .Must((x) => { return isPinCodeExists(x).Result; })
               .WithMessage("PinCode details not found !.");
        });
    }

    private Task<bool> isPinCodeExists(string isin)
    {
        // to check with database 
    }
}

I have also added DI to services in ASP.NET Core 8 Web API project as shown here:

services.AddTransient<IValidator<string?>, PinCodeValidator>();            

In the controller action method, I am validating using this code:

[HttpGet]        
public async Task<IActionResult> GetByPinCode([FromQuery] string? pincode)
{
    // validate
    this._isinValidator.ValidateAndThrowMISVAppException(pincode);           
}

Something is wrong with this code, I get an exception

Cannot pass null model to Validate. (Parameter 'instanceToValidate')

Any idea what I am doing wrong here?

3
  • 2
    Please check this thread: stackoverflow.com/questions/17095791/… Commented Jun 8, 2024 at 7:02
  • 1
    Specifically override PreValidate - see this information - docs.fluentvalidation.net/en/latest/advanced.html?#prevalidate Commented Jun 8, 2024 at 16:25
  • Based on your error message which indicates that, fluentValidation does not handle null values directly. In order to fix this, update the PinCodeValidator to explicitly handle null and empty values by adding NotNull and NotEmpty rules before the database check. Additionally, in the controller action method, check if the pincode is null before invoking the validator, returning a BadRequest if it is. This ensures that null and empty pin codes are managed appropriately, with the validator performing database checks only on valid, non-null pin codes. Commented Jun 12, 2024 at 5:42

0

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.