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?
PreValidate- see this information - docs.fluentvalidation.net/en/latest/advanced.html?#prevalidatePinCodeValidatorto explicitly handle null and empty values by addingNotNullandNotEmptyrules 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.