I've started using FluentValidation
on a WPF project, till now I used it in a simple way checking if a field has been filled or less then n character.
Now I've to check if the value inserted (which is a string...damn old code) is greater then 0. Is there a simple way I can convert it using
RuleFor(x=>x.MyStringField).Somehow().GreaterThen(0) ?
Thanks in advance
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");
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;
})
Another solution:
RuleFor(a => a.MyStringField).Must(x => int.TryParse(x, out var val) && val > 0)
.WithMessage("Invalid Number.");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With