2

Hello supposing i have a model with a field like this: (mvc5)

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> Date { get; set; }

In the razor view (3.0) i use the Html helper to show a date picker field, like this:

    @Html.EditorFor(model => model.reunion.Date)
    @Html.ValidationMessageFor(model => model.reunion.Date)

On the input on the html i will have something like this:

<input class="text-box single-line valid" data-val="true" data-val-date="The field Date must be a date." data-val-required="O campo Date é necessário." id="reunion_Date" name="reunion.Date" type="date" value="2017-01-01" aria-required="true" aria-describedby="reunion_Date-error" aria-invalid="false">

And the image of the picker of date:

Picker of date

It works fine.

But let's suppose i want to restrict the date the user can select to only dates that are equal or more than the actual date. What is the way i could do that?

3
  • Try to restrict by java-script function using maxDate and minDate
    – keerti
    Commented Jan 2, 2017 at 11:05
  • Why you are taking date as Nullable?
    – keerti
    Commented Jan 2, 2017 at 11:43
  • The date is Nullable date because generated the model from the database, where i left the option to allow nulls.
    – Nmaster88
    Commented Jan 2, 2017 at 11:46

2 Answers 2

2

Try like this -

<script type="text/javascript">

    $(document).ready(function () {
        $("#Date").datepicker({ minDate: -20, maxDate: "+1M +10D" });
    });
</script>
3
  • what is the issue coming with this solution?
    – keerti
    Commented Jan 2, 2017 at 11:34
  • check this - 20fingers2brains.blogspot.com/2013/05/…
    – keerti
    Commented Jan 2, 2017 at 11:36
  • Hi, because i was using an input of type date, chrome by defect uses a date picker, that's different from the one of the jquery UI. I'm a little confusing with this because i'm new to html 5, asp.net mvc...
    – Nmaster88
    Commented Jan 2, 2017 at 11:55
1

Create a custom attribute, here I have an example:

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

And in model is something like:

[FutureDateAtribute]
public DateTime mydateTime { get; set; }

Not the answer you're looking for? Browse other questions tagged or ask your own question.