leipzy
leipzy

Reputation: 12794

validate dates of jquery date picker textboxes

I'm using jquery date picker and I would like to verify the dates if the date from and date to is valid like date from should be less than date to

I'm using the jquery date picker code that can be found here

http://jqueryui.com/datepicker/#date-range

Upvotes: 0

Views: 895

Answers (1)

Chirag Vidani
Chirag Vidani

Reputation: 2587

As you plan to go using jQuery DatePicker, please implement 2 textboxes as per requirement of start and end dates.

Then on submission you can get selected date via getDate() method

var startDate = $( ".selector" ).datepicker( "getDate" );

This will return date typeof() value in javascript.

Now you can use conditional approach to compare dates.

Demo Example:

Include js files

<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

HTML

Start date: <input type="text" id="txtStartDate"> &nbsp;
End date: <input type="text" id="txtEndDate"> 

<input id="btnValidateDate" type="button" value="Validate Dates" />    

jQuery

$(function(){
    $( "#txtStartDate" ).datepicker();
    $( "#txtEndDate" ).datepicker();

    $('#btnValidateDate').click(function(){
        var startDate = $( "#txtStartDate" ).datepicker( "getDate" );
        var endDate =  $( "#txtEndDate" ).datepicker( "getDate" );
        if(startDate > endDate)
            alert('Invalid date! End date should be greater than start date.');
        else
            alert('Valid date');            
    });    
});

Refer this fiddle demo.

Upvotes: 1

Related Questions