Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataAnotation to validate a model, how do I validate it so that the date is not in the future?

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.

like image 347
Jung Avatar asked Sep 12 '17 20:09

Jung


1 Answers

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.

like image 154
Shyju Avatar answered Sep 22 '22 02:09

Shyju