I have the Review Model, I am trying to validate the model, so that when the user selects a date, it can't be the date in the future.
Review.cs
public class Review : BaseEntity{
[Key]
public int Id {get; set;}
[Required(ErrorMessage="You need a restaurant name!")]
public string RestaurantName {get; set;}
[What do I put in here??]
public DateTime Date {get; set;}
}
I am a newbie, and the documentation is kind of hard to understand.
Thank you so much for your help in advance.
You can create a custom validation attribute which does your custom logic and use that to decorate your property name.
public class DateLessThanOrEqualToToday : ValidationAttribute
{
public override string FormatErrorMessage(string name)
{
return "Date value should not be a future date";
}
protected override ValidationResult IsValid(object objValue,
ValidationContext validationContext)
{
var dateValue = objValue as DateTime? ?? new DateTime();
//alter this as needed. I am doing the date comparison if the value is not null
if (dateValue.Date > DateTime.Now.Date)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return ValidationResult.Success;
}
}
Now in your view model, decorate your property name with this new custom attribute
[DateLessThanOrEqualToToday]
public DateTime Date { get; set; }
This custom validation attribute is primarly focusing on your specific validation logic. You can alter it to include more null checks, minimum value check etc as needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With