After reviewing several articles and SO questions, I still cannot understand why my validation attributes are not triggering.
For simplicity, I have reduced my model and added the string testing
to debug.
using System;
using System.ComponentModel.DataAnnotations;
namespace PublicApi
{
public class CostStandardRequest
{
[DateLessThan("EndDate", ErrorMessage = "StartDate must be less than EndDate")]
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[Required]
public string testing { get; set; }
}
}
In my controller, I test my method by passing a null
value to the testing attribute in my CostStandardRequest
class. However, ModelState.IsValid
returns true despite null values.:
[HttpPost]
public async Task<ActionResult<string>> PostCostingStandard(CostStandardRequest request)
{
if (ModelState.IsValid)
{
// always valid
}
else
{
// never runs
}
}
I've reached this point by following the guide in the documentation
Note: ModelState.IsValid is true even when my custom validation attribute [DateLessThan] should be returning a ValidationResult(ErrorMessage)
. I have not included this code, but I can if it's deemed relevant.