Question: Date picker in razor view with restriction


Date picker in razor view with restriction

Answers 2
Added at 2017-01-02 12:01

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

[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?

Answers to

Date picker in razor view with restriction

nr: #1 dodano: 2017-01-02 12:01

Try like this -

<script type="text/javascript">

    $(document).ready(function () {
        $("#Date").datepicker({ minDate: -20, maxDate: "+1M +10D" });
nr: #2 dodano: 2017-01-03 10:01

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:

public DateTime mydateTime { get; set; }
Source Show
◀ Wstecz