简体   繁体   English

DatePicker JQuery UI从日期到日期的=>

[英]DatePicker JQuery UI valiadtion to date >= from date

Can anyone tell me how to do validation through class name (ie) .datepicker 谁能告诉我如何通过类名(即.datepicker )进行验证

Here is the demo to have a validation for to date >= from 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/ http://jsfiddle.net/sharmilashree/YdeY8/482/

You could use momentJS to validate if you date is before or equals. 您可以使用momentJS来验证日期是否早于或等于。
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. 在此示例中,第一个日期表示datetimepicker的值,第二个日期是您想要的日期,因为您从未告诉过它是什么。

I agree with using moment.js . 我同意使用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/ 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. 之所以必须将日期分成几部分,是因为javascript Date()对象仅解析特定格式,而您不能自定义格式。 This is why it is nice to use a library like moment.js , as it will handle everything very flexibly. 这就是为什么最好使用诸如moment.js类的库,因为它可以非常灵活地处理所有事情。

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 ; 假设您想在6个月内将日期从dd-mm-yy更改为dd/mm/yy you will have to go and update your string splitting code. 您将必须去更新您的字符串拆分代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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