test acc
test acc

Reputation: 41

validating date in the datepicker

I have two datepickers:

$(".From").datepicker({
dateFormat: 'dd/mm/yy',
numberOfMonths: 1,
autoclose: true,
onClose: function(selectedDate) {
    $(".To").datepicker("option", "minDate", selectedDate);
}});


$(".To").datepicker({
dateFormat: 'dd/mm/yy',
numberOfMonths: 1,
autoclose: true,
onClose: function(selectedDate) {
    $(".From").datepicker("option", "maxDate", selectedDate);
}});

View:

 @Html.TextBoxFor(model => model.From, new { @class = "form-control From" })
 @Html.TextBoxFor(model => model.To, new { @class = "form-control To" })

Model:

    [Display(Name = "From")]
    public string From { get; set; }

    [Display(Name = "To")]
    public string To { get; set}; 

When the user manually enters the date, it fails.

Is there a way to allow users to enter the date and validate it?

option 1: Should I use regex?

Upvotes: 4

Views: 2233

Answers (1)

Jasen
Jasen

Reputation: 14250

Here's a working example

Model

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
[DisplayName(Name = "From")]
public DateTime? From { get; set; }  // note the data type

View

@Html.TextBoxFor(model => model.From, new { @class = "form-control From" })
@Html.ValidationMessageFor(model => model.From)

Don't forget to load the validation scripts.

jquery.validate.js
jquery.validate.unobtrusive.js 

This will give you a validation error message when you attempt to type a bad date.

Upvotes: 1

Related Questions