Reputation: 139
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
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
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
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")" />
Upvotes: 7