Validate that end date is greater than start date with jQuery

前端 未结 15 1656
隐瞒了意图╮
隐瞒了意图╮ 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:44

    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

    0 讨论(0)
  • 2020-11-22 13:46

    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 :-)

    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题