views:

409

answers:

2

I am using jquery bassistance validation and need to verify that a start date is after an end date. I am wondering if anyone knows if this functionality exists and if I can add rules to do this or if I have to add a custom check. I am having difficulty finding any examples of this that work with my code which forwards to another function if the form is valid. (pasted below)

$("#hotels").validate({
    rules: {
        checkinDate: {
            date: true
        },
        checkoutDate: {
            date: true
        }
    }
});


$("#hotels input.submit").click(function() {
  var isValid = $("#hotels").valid();
  if (isValid == true) {
      } else {
          hComp();
          return false;
      }
  } else {
      return false;
  }
});

I saw this in another example, but am not sure how I could use it.

var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());

if (startDate < endDate){
// Do something
}

Thanks in advance for any assistance.

A: 

That example looks like it's exactly what you need. Have a look here.

Borrowing from that jquery example, suppose you have the following HTML:

  <input id="startDate" value="Jan 12, 2009" />
  <input id="endDate" value="Jan 12, 2010" />

Then this JavaScript code should show the alert "Start date is before end date!" (assuming the values aren't modified):

var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());

if (startDate < endDate){
    alert("Start date is before end date!");
}
Dan Breslau
Thanks. This clarifies things. My date format is mm/dd/yy. I think that is the issue.
ks
A: 

I ended up solving this problem before validation, which is probably a much better idea anyway. Here's the solution using the jquery ui datepicker. Then I can just use the same logic to do a final validation check.

$('input').filter('.datepicker').datepicker({

beforeShow: customRange, showOn: 'both', buttonImage: contextPath + '/assets/images/icon-calendar.gif', buttonImageOnly: true, buttonText: 'Show Date Picker' });

function customRange(a) {
var b = new Date();
var c = new Date(b.getFullYear(), b.getMonth(), b.getDate());
if (a.id == 'checkoutDate') {
if ($('#checkinDate').datepicker('getDate') != null) {
c = $('#checkinDate').datepicker('getDate');
}
}
return {
minDate: c
}
}

ks