Just write a custom validator like this
public class Validator : AbstractValidator<Test>
{
public Validator()
{
RuleFor(x => x.MyString)
.Custom((x, context) =>
{
if ((!(int.TryParse(x, out int value)) || value < 0))
{
context.AddFailure($"{x} is not a valid number or less than 0");
}
});
}
}
And from your place where you need to validate do this
var validator = new Validator();
var result = validator.Validate(test);
Console.WriteLine(result.IsValid ? $"Entered value is a number and is > 0" : "Fail");
Update 11/8/21
If you are going to use this on a large project or API, you are probably better by doing this from the Startup
and we don't need to manually call the validator.Validate()
in each and every method.
services.AddMvc(options => options.EnableEndpointRouting = false)
.AddFluentValidation(fv =>
{
fv.RegisterValidatorsFromAssemblyContaining<BaseValidator>();
fv.ImplicitlyValidateChildProperties = true;
fv.ValidatorOptions.CascadeMode = CascadeMode.Stop;
})