Search code examples
javascriptjqueryjquery-uirazorjquerydatetimepicker

DatePicker JQuery UI valiadtion to date >= from date


Can anyone tell me how to do validation through class name (i.e) .datepicker

Here is the demo to have a validation for to date >= from date

$('.datepicker').datepicker({
changeYear: true,
dateFormat: "dd-mm-yy", 
yearRange: '2006:' + (new Date().getFullYear() +1)
}).datepicker("setDate", "0");

http://jsfiddle.net/sharmilashree/YdeY8/482/


Solution

  • I agree with using moment.js. However, if you for some reason don't want to, or can't, here is a solution for your fiddle.

    http://jsfiddle.net/jonofan/YdeY8/483/

    $('.datepicker').on('change', function() {
          var fromParts = $('#CheckInDate').val().split('-');       
          var toParts = $('#CheckOutDate').val().split('-');
    
          //please put attention to the month (parts[0]), Javascript counts months from 0:
          // January - 0, February - 1, etc
    
          var fromDate = new Date(fromParts[2],fromParts[0]-1,fromParts[1]); 
          var toDate = new Date(toParts[2],toParts[0]-1,toParts[1]); 
    
          if ( fromDate >= toDate ) {
            alert('Check in must be before check out!')
          }
        })
    

    The reason you must split your date into parts is because the javascript Date() object only parses specific formats, and you cannot custom formats. This is why it is nice to use a library like moment.js, as it will handle everything very flexibly.

    From experience, using string splitting to parse dates becomes problematic in the event that you want to change the date format. Say in 6 months you wanted to change your dates from dd-mm-yy to dd/mm/yy; you will have to go and update your string splitting code.