Mvc checks date / time for at least 1 minute in the future

I'm still hugging MVC.

I saw several similar questions, some kind of custom code and various methods, but I did not find what works for me.

I have a search model that populates an HTML table with results inside a partial view. I have this in my model of search results:

public DateTime? BeginDateTime { get; set; } 

What is set in DateTime.Now in the controller. The user can specify this date and time to start the task with the data of the search results by calling the POST model.

What I would like to do is confirm that the date / time that the user determined is at least 1 minute in the future. If this can be done as a check on the client side, it will be better, but I am open to options while it works.

View:

 Begin update: @Html.TextBoxFor(o => o.BeginDateTime, new { id="txtBegin" }) 

Thanks.

+4
source share
2 answers

Create a new attribute:

 public class FutureDateAttribute : ValidationAttribute { public override bool IsValid(object value) { return value != null && (DateTime)value > DateTime.Now; } } 

Now in your model set this attribute:

 [FutureDate(ErrorMessage="Date should be in the future.")] public DateTime Deadline { get; set; } 
+7
source

This is another good way to verify that the selected date is selected from the future.

 public class FutureDate : ValidationAttribute { public override bool IsValid(object value) { DateTime dateTime; var isValid = DateTime.TryParseExact( //Getting the value from the user. Convert.ToString(value), //We want the user to enter date in this format. "d mmm yyyy", //It checks if the culture is us-en CultureInfo.CurrentCulture, //Mosh has no idea what this does. DateTimeStyles.None, //Output parameter. out dateTime); return (isValid && dateTime > DateTime.Now); } } 
0
source

All Articles