简体   繁体   中英

DatePicker JQuery UI valiadtion to date >= from date

Can anyone tell me how to do validation through class name (ie) .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/

You could use momentJS to validate if you date is before or equals.
A simple code like :

if(moment(fistDate).isBefore(moment(secondDate)) || moment(firstDate).isSame(moment(secondDate)) {

}

In this example, the first date represent the value of your datetimepicker and the second date is whatever you want it to be since you never told what it was.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM