8

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.

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Just as a side note, why doesn't the disabling of dates in the datepicker beyond the min/max work if I change the date format in the ToString to anything else, like "dd-MM-yyyy HH:mm"? (Validation still works fine, but need to show the errors in the validation as perfectly readable to the user, while retaining the disabled dates).
You can see this article.
Is there any way to set a custom error for min and max?
7

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;}

Comments

2

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; }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.