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
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
That should do it I think
i came across this code. how can i use this method to validate the textbox?
$.validator.addMethod('greaterThan', function(value, element, param) { return ( IsNaN( value ) && IsNaN( $(param).val() ) ) || ( value > $(param).val() ); }, 'Must be greater than {0}.' );
$.validator.addMethod('lesserThan', function(value, element, param) { return ( IsNaN( value ) && IsNaN( $(param).val() ) ) || ( value < $(param).val() ); }, 'Must be lesser than {0}.' );
where would i pass the parameters of startDate and endDate?
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/
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);
}, "* End date must be after start date");
$('#formId').validate();
});
</script>
Hope this helps :-)
Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers
jQuery.validator.addMethod("greaterThan", function(value, element, params) {
if (!/Invalid|NaN/.test(new Date(value))) { return new Date(value) > new Date($(params).val()); } return isNaN(value) && isNaN($(params).val()) || (parseFloat(value) > parseFloat($(params).val())); },'Must be greater than {0}.');