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