ASP.NET Core Web API - Fluent Validation not validation against null datetime

Viewed 54

In my ASP.NET Core-6 Web API, I have this fields in a model:

public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }

Then I have this Fluent Validations:

RuleFor(m => m.StartDate)
    .NotEmpty().WithMessage("Start Date field is required. ERROR!")
    .NotNull().WithMessage("Start Date cannot be null");

RuleFor(m => m.EndDate)
    .NotEmpty().WithMessage("End Date field is required. ERROR!")
    .NotNull().WithMessage("End Date cannot be null");

RuleFor(m => m).Must(m => m.EndDate == default(DateTime) || m.StartDate == default(DateTime) || m.EndDate > m.StartDate)
        .WithMessage("End Date must greater than Start Date");

This validation End Date must greater than Start Date is working fine.

But where I have issue is that whenever StartDate or EndDate is null on the POSTMAN as shown below:

"startDate": "", "endDate": ""

I got this error:

"errors": {
    "endDate": [
        "Error converting value {null} to type 'System.DateTime'. Path 'endDate', line 4, position 15."
    ],
    "startDate": [
        "Error converting value {null} to type 'System.DateTime'. Path 'startDate', line 3, position 17."
    ]

How do I resolve this?

Thanks

1 Answers

You need to make DateTime a nullable type:

public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }

In my opinion, this is not actually related to FluentValidation.

During model binding, asp.net core will attempt to convert the incoming value to the type of the property. If it can’t, then it will generate the errors you’re seeing. This is a part of asp.net itself and happens before asp.net invokes FluentValidation, so we cannot intercept or customise this process as it is part of model binding. Validation providers are only invoked by asp.net once this phase completes without errors.

Note that this only happen for non-nullable value types (such as int, datetime etc), as null values literally can’t be assigned to properties of this type. If you make the properties nullable, then passing a null value in will succeed, and FluentValidation will be given a chance to execute (you can then have a NotNull rule at the FluentValidation level).

So just to reiterate this is not a behaviour of FluentValidation, this is part of asp.net core itself. It cannot he turned off and is controlled entirely by the nullability of the property types.

Hope this can help you.

Related