我已经写了一个日期验证属性-
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
{
return ValidationResult.Success;
}
Match regExMatch = Regex.Match(value.ToString().Trim(), @"(^(((0[1-9]|1[0-9]|2[0-8])[\/](0[1-9]|1[012]))|((29|30|31)[\/](0[13578]|1[02]))|((29|30)[\/](0[4,6,9]|11)))[\/](19|[2-9][0-9])\d\d$)|(^29[\/]02[\/](19|[2-9][0-9])(00|04|08|12|16|20|24|28|32|36|40|44|48|52|56|60|64|68|72|76|80|84|88|92|96)$)");
if (regExMatch.Success)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(ErrorMessage);
}
}
我的cshtml是-
<div class="col-md-4">
@Html.EditorFor(model => model.History.TheDate, new { htmlAttributes = new { @class = "form-control", @type = "date" } })
@Html.ValidationMessageFor(model => model.History.TheDate, "", new { @class = "text-danger" })
</div>
我的模型是-
[DateValidator(ErrorMessage = "test")]
[Display(Name = "2020/21 Date?"), DateRangeTheDateAttibute(ErrorMessage = "Date must be after 28/09/2020"), DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? TheDate { get; set; }
如果用户输入无效的日期,例如31/02/2021,则对象值为null。我希望能够接受空日期,但标记无效日期。
任何帮助都是最好的!
发布于 2021-03-01 23:34:08
您不能在datetime?
对象中输入无效的日期,即使您在验证时接受无效的日期值。由于datetime
类型的限制和规则。
https://stackoverflow.com/questions/66424275
复制相似问题