1

I have an MVC application where I a model with Date property

 [Required(ErrorMessage = "This is a required field.")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public DateTime EventDate { get; set; }

I'm calling this in my view like this.

  <div class="col-sm-9">
        <span style="color:black">@Html.EditorFor(model => model.EventDate)</span><br />
        @Html.ValidationMessageFor(m => m.EventDate, "", new { @class = "text-danger" })
    </div>

Is there any way to disable past date while choosing a date. I tried to create a custom validation.

public class MyDateAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        DateTime d = Convert.ToDateTime(value);
        return d > DateTime.Now;

    }
}

and use it, but this removes the choosing a date enter image description here

is it possible to disable past date on this Datetime annotation ?

Anyhelp is greatly appreciated.

Thank you

ISHIDA
  • 4,700
  • 2
  • 16
  • 30
  • I think your check has to be `d > DateTime.Now` (future dates are "greater than" today). So you need to return true if it is a valid value. – Styxxy Oct 16 '17 at 19:20
  • @Styxxy I made those changes, It removed the calender dialog window for selecting the date. – ISHIDA Oct 16 '17 at 19:56
  • Try adding a `min` attribute: https://stackoverflow.com/questions/23671407/restrict-future-dates-in-html-5-data-input – Steve Greene Oct 16 '17 at 20:03
  • Validation attributes have nothing to do with how form controls are displayed in the view - they are for validating the value, and if invalid, then you display an error message. You have `[DataType(DataType.Date)]` in conjunction with `EditorFor()` which generates the browsers HTML-5 datepicker. That is supported in Chrome and Edge only and will render just a textbox in say FireFox. In any case, it must be `[DisplayFormat(DataFormatString = "{0: yyyy-MM-dd}", ApplyFormatInEditMode = true)]` to work correctly. –  Oct 16 '17 at 23:39
  • If you want a consistent UI and be able to restrict selecting dates, then use a jQuery datepicker (e.g. [jquery-ui] datepicker(https://jqueryui.com/datepicker/#min-max). And as a side note, your attribute does not give client side validation since it does not implement `IClientValidatable` - refer [The Complete Guide To Validation In ASP.NET MVC 3 - Part 2](https://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) –  Oct 16 '17 at 23:41

0 Answers0