I am making a custom validation attribute for the first time. It is for the TillDate to be greater or equal to the FromDate. I am getting the following error for the FromDate
System.FormatException: 'The string 'FromDate' was not recognized as a valid DateTime. There is an unknown word starting at index '0'.'
I am not sure about why this error is coming, whether it is because of something wrong in the Validation Attribute or something else.
Any help will be appreciated. Thank you!!
This is the customAttribute class
public class EndDateGreaterValidationAttribute : ValidationAttribute
{
public string _FromDate { get; private set; }
public EndDateGreaterValidationAttribute(string FromDate)
{
_FromDate = FromDate;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime _EndDat = DateTime.Parse(value.ToString());
DateTime? _fromDate = DateTime.Parse(_FromDate);
int cmp = _EndDat.CompareTo(_fromDate);
if (cmp > 0)
{
// date1 is greater means date1 is comes after date2
return ValidationResult.Success;
}
else if (cmp < 0)
{
// date2 is greater means date1 is comes after date1
return new ValidationResult(ErrorMessage);
}
else
{
// date1 is same as date2
return ValidationResult.Success;
}
}
}
This is the View model to the properties of which the attribute is applied
public class ApplyLeaveViewModel : ApplicationUser
{
[DisplayName("Date Applied")]
public DateTime DateApplied { get; set; }
public ApplyLeaveViewModel()
{
DateApplied = DateTime.Now;
}
[DisplayName("From Date")]
public DateTime FromDate { get; set; }
[DisplayName("Till Date")]
[EndDateGreaterValidation ( "FromDate", ErrorMessage = "End date must be greater than start date")]
public DateTime TillDate { get; set; }
}
This is the View
<div class="form-row mt-3">
<div class="form-group col-6">
@*<label class=" col-form-label small form-text">Date Applied On:</label>*@
@*<label asp-for="@Model.DateApplied" class="col-form-label small form-text">Date Applied:</label>*@
<div class="col">
<input type="text" hidden asp-for="@Model.DateApplied">
</div>
</div>
</div>
<div class="form-label mt-3">
<label class="col-form-label small form-text">Date(s) Requested For:</label>
</div>
<div class="form-row">
<div class="form-group col-md-6 ">
<label asp-for="FromDate" class="col-auto col-form-label small form-text">From Date:</label>
<div class="col">
<input asp-for="FromDate" type="date" class="form-control datepicker" />
<span asp-validation-for="FromDate" class="text-danger"></span>
@Html.ValidationMessageFor(model => model.FromDate)
</div>
</div>
<div class="form-group col-md-6 ">
<label asp-for="TillDate" class="col-auto col-form-label small form- text">Till Date:</label>
<div class="col">
<input asp-for="TillDate" type="date" class="form-control datepicker" />
<span asp-validation-for="TillDate" class="text-danger"></span>
@Html.ValidationMessageFor(m => m.TillDate)
</div>
</div>
</div>