Nightingale
Nightingale

Reputation: 139

Setting minimum and maximum date range to DateTime input

Is there a way to set a range for DateTime in the View Model, in a way that makes the maximum possible date one can input be the current date and time (UTC), and the minimum date possible be a year ago?

Something like [Range(typeof(DateTime), "06/06/2020 23:43", "Utc.Now")]?

Thank you in advance.

Upvotes: 8

Views: 9376

Answers (3)

Alex
Alex

Reputation: 21

I modified answer from Majid Qafouri

It works good!

    using System.ComponentModel.DataAnnotations;


    public class ValidateDateAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid
            (object obj, ValidationContext validationContext)
        {
            DateTime date = Convert.ToDateTime(obj);

            return (date <= DateTime.UtcNow && date >= DateTime.UtcNow.AddYears(-1))
                ? ValidationResult.Success
                : new ValidationResult("Invalid date range");
        }
    }

And your property should be decorated with the attribute

    [ValidateDate]
    public DateTime Created { get; set; }

Upvotes: 2

Matt Ghafouri
Matt Ghafouri

Reputation: 1577

If you want to validate the DateTime range on server-side, you would define a custom attribute to validate your property value.

    public class ValidateDate: ValidationAttribute
    {
        protected override ValidationResult IsValid
                         (object date, ValidationContext validationContext)
        { 
             return (date<= DateTime.Now && date >= DateTime.Now.AddYears(-1))
                 ? ValidationResult.Success
                 : new ValidationResult("Invalid date range"); 
        }
    }

And your property should be decorated with the attribute

[ValidateDate]
public DateTime MyDate{get; set;}

Upvotes: 7

Yinqiu
Yinqiu

Reputation: 7190

If you want to restrict user input, you can set the following settings on your view.

<input asp-for="SelectedDate" max="@DateTime.Now.ToString("yyyy-MM-ddThh:mm")" min="@DateTime.Now.AddYears(-1).ToString("yyyy-MM-ddThh:mm")" />

Result: enter image description here

Upvotes: 7

Related Questions