Validate that end date is greater than start date with jQuery

前端 未结 15 1661
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:14

How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?

15条回答
  •  隐瞒了意图╮
    2020-11-22 13:47

    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/

提交回复
热议问题