Restrict Date Range in jQuery DatePicker in MVC3 Razor



  1. In this article we will see how to restrict date range in jQuery DatePicker.
  2. We often have a requirement where we have a minimum date, before which we do not want to select date, or in other way we have a maximum date.
  3. In such scenarios we want to restrict date range in jQuery DatePicker.

Following are the steps :

ViewModel :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace jQueryDatePicker.Models
{
    public class Register
    {
        public DateTime DOB { get; set; }
    }
}

We have created a ViewModel which contains DOB property. We will bind this ViewModel to view to render control for this property. The property is of type DateTime.

View :



@model jQueryDatePicker.Models.Register
@{
    Layout = "../Shared/_Layout.cshtml";
}

<!DOCTYPE html>
@Html.EditorFor(Model => Model.DOB)

<script type="text/javascript">

    $(document).ready(function () {
        $("#DOB").datepicker({ minDate: -20, maxDate: "+1M +10D" });
    });
</script>

In the above view we have binded the DOB property. We are rendering datepicker on clicking the textbox. We have restricted the date range by using minDate and maxDate property. According to above properties we cannot select date futher to 20 days before today and in the same way 1 month and 10 days after today.

Layout :



<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.8.3.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.datepicker.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.widget.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.ui.core.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
</head>

<body>
    @RenderBody()
</body>
</html>

We have to include above references of jQuery script files for using DatePicker.

Demo :


Click inside textbox to open DatePicker.


By following steps we can restrict date range in jQuery DatePicker.

0 comments:

Post a Comment