magna_nz
magna_nz

Reputation: 1273

Fluentvalidation only validate if field is populated

I have a decimal field like:

public decimal Limit {get; set;}

Now, I'm trying to use fluent validation for a rule like:

This field is not mandatory but if it IS populated, then validate its greater than 0. If it isn't populated, then ignore it

How can I do this? My problem a decimal defaults to 0 anyway, so how can I determine if it's been populated with a 0 or not?

I've been trying something like :

When(x => x.Limit== 0, () =>
{
  RuleFor(x => x.Limit)
    .Empty()
    .GreaterThan(0)
    .WithMessage("{PropertyName} sflenlfnsle Required");
})

Upvotes: 3

Views: 3030

Answers (1)

Mashton
Mashton

Reputation: 6415

As stated in the comment, the only way to distinguish between a value type which hasn't been set (and so has the default value) and one which has been set to the default value is to change the type to a nullable type.

void Main()
{

    var example1 = new SomeType();                  // Limit not set, should pass validation
    var example2 = new SomeType(){Limit = 0};       // Limit set, but illegal value, should fail validation
    var example3 = new SomeType(){Limit = 10.9m};   // Limit set to legal value, should pass validation

    var validator = new SomeTypeValidator();

    Console.WriteLine(validator.Validate(example1).IsValid);    // desired is 'true'
    Console.WriteLine(validator.Validate(example2).IsValid);    // desired is 'false'
    Console.WriteLine(validator.Validate(example3).IsValid);    // desired is 'true'
}


public class SomeType
{
    public Decimal? Limit { get; set; }
}

public class SomeTypeValidator : AbstractValidator<SomeType>
{
    public SomeTypeValidator()
    {
        RuleFor(r=>r.Limit.Value)
            .NotEmpty()
            .When(x=> x.Limit.HasValue);
    }
}

Upvotes: 2

Related Questions