Sunday, 16 November 2014

StartDate-EndDate validation with Kendo datepicker and MVC

 If we have two DatePicker controls for StartDate and EndDate and we are writing long validation methods to check if user has given start date greater than end date etc., we can try something else - We can restrict user to select wrong dates.
 
To explain, if user has selected StartDate as 1st Jan 2014, then the EndDate control should populate dates starting from 1st Jan 2014 and not the previous dates.
 
On the other hand, if user selects EndDate first as say 10th Jan 2014, then StartDate should have a maximum selectable date as 10th Jan 2014 and not the dates after that. 
 
Restricting user to select wrong dates at the time of input is obviously better than checking after user clicks a button and expects some output. This improves user experience.
 
This is how we can implement this using KendoUI and MVC - 
 
<label for="start"> Start Date </label>
@(Html.Kendo().DatePicker()
    .Name("start")
    .Events(e => e.Change("StartDateChanged"))
)

<label for="end"> End Date </label>
@(Html.Kendo().DatePicker()
    .Name("end")
    .Events(e => e.Change("EndDateChanged"))
)

<script type="text/javascript">
    
    function StartDateChanged() {
        var startDate = this.value();
        var endPicker = $("#end").data("kendoDatePicker");
        
        if (startDate) {
            startDate = new Date(startDate);
            startDate.setDate(startDate.getDate());
            endPicker.min(startDate);
        }
        else {
                
        }
    }

    function EndDateChanged() {
        var endDate = this.value();
        var startPicker = $("#start").data("kendoDatePicker");

        if (endDate) {
            endDate = new Date(endDate);
            endDate.setDate(endDate.getDate());
            startPicker.max(endDate);
        }
    }
</script>
 
It will show only the valid Dates to user and user can select from there only.

1 comment: