How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?
If the format is guaranteed to be correct YYYY/MM/DD and exactly the same between the two fields then you can use:
if (startdate > enddate) {
alert('error'
}
As a string comparison
Reference jquery.validate.js and jquery-1.2.6.js. Add a startDate class to your start date textbox. Add an endDate class to your end date textbox.
Add this script block to your page:-
<script type="text/javascript">
$(document).ready(function() {
$.validator.addMethod("endDate", function(value, element) {
var startDate = $('.startDate').val();
return Date.parse(startDate) <= Date.parse(value) || value == "";
}, "* End date must be after start date");
$('#formId').validate();
});
</script>
Hope this helps :-)
The date values from the text fields can be fetched by jquery's .val() Method like
var datestr1 = $('#datefield1-id').val();
var datestr2 = $('#datefield2-id').val();
I'd strongly recommend to parse the date strings before comparing them. Javascript's Date object has a parse()-Method, but it only supports US date formats (YYYY/MM/DD). It returns the milliseconds since the beginning of the unix epoch, so you can simply compare your values with > or <.
If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.
If you want to be super user-fiendly, you can use jquery ui datepickers instead of textfields. There is a datepicker variant that allows to enter date ranges:
http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/