I have 2 binding fields in a Razor page as shown below:
CSHTML.CS
[BindProperty]
[Required(ErrorMessageResourceType = typeof(MsgsResource), ErrorMessageResourceName = MandatoryFld)]
[CompareDate("DateTo", ComparisonType.LessThanOrEqualTo, ErrorMessageResourceType = typeof(MsgsResource), ErrorMessageResourceName = DateFromNotOk)]
public DateTime DateFrom { get; set; }
[BindProperty]
[Required(ErrorMessageResourceType = typeof(MsgsResource), ErrorMessageResourceName = MandatoryFld)]
[CompareDate("DateFrom", ComparisonType.GreaterThanOrEqualTo, ErrorMessageResourceType = typeof(MsgsResource), ErrorMessageResourceName = DateToNotOk)]
public DateTime DateTo { get; set; }
CSHTML
<div class="mb-4">
<div class="row">
<div class="col-6">
<label asp-for="DateFrom" class="form-label text-muted fw-semibold mb-3">@CommonResource.FromDate</label>
@Html.TextBoxFor(m=> m.DateFrom, new { @class="form-control flatpickr flatpickr-input", type = "date", data_provider="flatpickr" })
<span class="invalid-feedback" asp-validation-for="DateFrom"></span>
</div>
<div class="col-6">
<label asp-for="DateTo" class="form-label text-muted fw-semibold mb-3">@CommonResource.ToDate</label>
@Html.TextBoxFor(m=> m.DateTo, new { @class="form-control flatpickr flatpickr-input", type = "date", data_provider="flatpickr" })
<span class="invalid-feedback" asp-validation-for="DateTo"></span>
</div>
</div>
</div>
Both dates default to a specific date with a difference of say 30 days apart from today.
I have this custom attribute, CompareDate
, to verify the following in both server and client-side:
- DateFrom is >= DateTo
- DateTo is <= DateFrom
During a Ajax call to retrieve records on a OnPost
method, model validations will be triggered. The first check will fail because DateTo
has a value of DateTime.MinValue
(not its default value). On the 2nd validation check, both DateFrom
and DateTo
are as per their default values and hence the validation is ok.
I just wonder why DateTo
is set to DateTime.MinValue
even though it has a default value in the first check. Seems like I can only set the CompareDate
validation on DateTo
only.
Please advise. Thanks.