0

谁能告诉我如何通过类名(即).datepicker进行验证

这是验证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/

4

2 回答 2

0

您可以使用momentJS来验证您的日期是否早于或等于。
一个简单的代码,如:

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

}

在此示例中,第一个日期表示您的 datetimepicker 的值,第二个日期是您想要的任何日期,因为您从未告诉过它是什么。

于 2017-02-16T18:21:15.407 回答
0

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.

于 2017-02-16T18:45:04.247 回答