Validating DateTime Fluent Validation + IPatchDb

Hi,

I’ve come across an issue where I was having trouble get FluentValidation to validate a DateTime property when it has not supplied by the user.

It does try and validate a DateTime property if a valid date is supplied (I created a temporary custom validation to fail if the date is in the future to fail on purpose)

public class UpdateX : IPatchDb<X>, IReturn<X>
{
    public required int Id { get; set; }
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public DateTime DOB { get; set; }
}
  public class XValidator : AbstractValidator<UpdateX>
    {
        public XValidator()
        {
            RuleSet(ApplyTo.Patch, () =>
            {
                RuleFor(x => x.FirstName).NotNull().NotEmpty();
                RuleFor(x => x.LastName).NotNull().NotEmpty();
                RuleFor(x => x.DOB).NotNull().NotEmpty();
            });
        }
    }

After spending a lot of time experimenting, I removed the IPatchDb interface and manually created a service to handle the model, FluentValidation picks up the DateTime property and fails it accordingly.

The other properties work as intended and I wanted to make sure this was a bug or something I’m not doing correctly.

All non PK properties on an IPatchDb<T> API need to be optional/nullable, i.e. it should be changed to DateTime? DOB.

It also isn’t a good idea to validate an IPatchDb<T> API for nullable values since it only updates and is populated with properties that have changed, i.e. all other properties would remain empty.

I’ve changed it to DateTime? DOB and it still has the same behaviour.

Should I be using the Put api instead if I’m planning on letting the user update information and need to check if they have omitted mandatory fields?

IPatchDb<T> default HTTP method is PATCH, IUpdateDb<T> uses PUT.

Your mandatory fields should be validated when creating the record, IPatchDb is only for updating existing properties. If you want all properties to be updated instead of only changed properties use IUpdateDb.

1 Like