使用jQuery验证结束日期大于开始日期

时间:2022-12-01 08:35:36

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

我如何在jQuery中检查/验证结束日期[文本框]是否大于起始日期[文本框]?

13 个解决方案

#1


152  

Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers

只是扩大了融合的答案。这个扩展方法使用jQuery validate插件。它将验证日期和数字。

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()) 
        || (Number(value) > Number($(params).val())); 
},'Must be greater than {0}.');

To use it:

使用它:

$("#EndDate").rules('add', { greaterThan: "#StartDate" });

or

$("form").validate({
    rules: {
        EndDate: { greaterThan: "#StartDate" }
    }
});

#2


74  

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

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

That should do it I think

我认为应该这样

#3


15  

Little late to the party but here is my part

参加聚会的时间并不晚,但这是我的部分

Date.parse(fromDate) > Date.parse(toDate)

Date.parse(fromDate)> Date.parse(迄今为止)

Here is the detail:

这是细节:

var from = $("#from").val();
var to = $("#to").val();

if(Date.parse(from) > Date.parse(to)){
   alert("Invalid Date Range");
}
else{
   alert("Valid date Range");
}

#4


14  

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.

参考jquery.validate。js和jquery-1.2.6.js。在开始日期文本框中添加一个startDate类。在结束日期文本框中添加一个endDate类。

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

希望这有助于:-)

#5


13  

I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date constructor, but others will not. For example, Chrome 18 gives

我只是在修改danteuno的答案,发现虽然出于好意,但遗憾的是,它在几个浏览器上都被破坏了。这是因为IE会对它接受的日期构造函数参数非常严格,而其他的则不会。例如,Chrome 18给出了。

> new Date("66")
  Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)

This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11") is greater than new Date("66") and this is obviously the opposite of the desired effect).

这导致代码采用“比较日期”路径,从这里开始,一切都走下坡路(例如,new Date(“11”)大于new Date(“66”),这显然与期望的效果相反)。

Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().

因此,在考虑之后,我修改了代码,使“数字”路径优先于“日期”路径,并使用JavaScript中的validate decimal numbers—IsNumeric()中提供的优秀方法验证输入确实是数字的。

In the end, the code becomes:

最后,代码变为:

$.validator.addMethod(
    "greaterThan",
    function(value, element, params) {
        var target = $(params).val();
        var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
        var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
        if (isValueNumeric && isTargetNumeric) {
            return Number(value) > Number(target);
        }

        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date(target);
        }

        return false;
    },
    'Must be greater than {0}.');

#6


5  

The date values from the text fields can be fetched by jquery's .val() Method like

可以通过jquery的.val()方法获取文本字段的日期值

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 <.

我强烈建议在比较日期字符串之前先解析它们。Javascript的Date对象有一个parse()-Method,但它只支持US的日期格式(yyyyy /MM/DD)。它返回unix纪元开始后的毫秒数,因此您可以简单地将您的值与>或 <进行比较。< p>

If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.

如果您想要不同的格式(例如ISO 8661),您需要使用正则表达式或空闲日期。js库。

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:

如果你想成为超级用户狂,你可以使用jquery ui datepickers而不是textfields。有一个datepicker变体允许输入日期范围:

http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/

http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/

#7


3  

So I needed this rule to be optional and none of the above suggestions are optional. If I call the method it is showing as required even if I set it to needing a value.

所以我需要这个规则是可选的,上面的建议都不是可选的。如果我调用这个方法,它会按需要显示,即使我将它设置为需要一个值。

This is my call:

这是我的电话:

  $("#my_form").validate({
    rules: {
      "end_date": {
        required: function(element) {return ($("#end_date").val()!="");},
        greaterStart: "#start_date"
      }
    }
  });//validate()

My addMethod is not as robust as Mike E.'s top rated answer, but I'm using the JqueryUI datepicker to force a date selection. If someone can tell me how to make sure the dates are numbers and have the method be optional that would be great, but for now this method works for me:

我的addMethod不如Mike E那么健壮。但我正在使用JqueryUI datepicker来强制选择日期。如果有人能告诉我如何确定日期是数字,并让方法是可选的,那就太好了,但是现在这个方法对我有效:

jQuery.validator.addMethod("greaterStart", function (value, element, params) {
    return this.optional(element) || new Date(value) >= new Date($(params).val());
},'Must be greater than start date.');

#8


2  

I like what Franz said, because is what I'm using :P

我喜欢弗兰兹说的,因为我用的是P。

var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}

#9


2  

$(document).ready(function(){
   $("#txtFromDate").datepicker({
        minDate: 0,
        maxDate: "+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });

    $("#txtToDate").datepicker({
        minDate: 0,
        maxDate:"+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });
});

Or Visit to this link

或者访问这个链接

#10


2  

In javascript/jquery most of the developer uses From & To date comparison which is string, without converting into date format. The simplest way to compare from date is greater then to date is.

在javascript/jquery中,大多数开发人员使用的是从&到日期的比较是字符串,没有转换成日期格式。最简单的比较日期的方法是更大的日期。

Date.parse(fromDate) > Date.parse(toDate)

Always parse from and to date before comparison to get accurate results

在进行比较之前,始终要对数据进行解析,以得到准确的结果

#11


1  

function endDate(){
    $.validator.addMethod("endDate", function(value, element) {
      var params = '.startDate';
        if($(element).parent().parent().find(params).val()!=''){
           if (!/Invalid|NaN/.test(new Date(value))) {
               return new Date(value) > new Date($(element).parent().parent().find(params).val());
            }
       return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) > parseFloat($(element).parent().parent().find(params).val())) || value == "";              
      }else{
        return true;
      }
      },jQuery.format('must be greater than start date'));

}

function startDate(){
            $.validator.addMethod("startDate", function(value, element) {
            var params = '.endDate';
            if($(element).parent().parent().parent().find(params).val()!=''){
                 if (!/Invalid|NaN/.test(new Date(value))) {
                  return new Date(value) < new Date($(element).parent().parent().parent().find(params).val());
            }
           return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) < parseFloat($(element).parent().parent().find(params).val())) || value == "";
                 }
                        else{
                     return true;
}

    }, jQuery.format('must be less than end date'));
}

Hope this will help :)

希望这能有所帮助。

#12


1  

jQuery('#from_date').on('change', function(){
    var date = $(this).val();
    jQuery('#to_date').datetimepicker({minDate: date});  
});

#13


-2  

If the format is guaranteed to be correct YYYY/MM/DD and exactly the same between the two fields then you can use:

如果格式保证是正确的yyyyy /MM/DD,并且两个字段之间的格式完全相同,那么您可以使用:

if (startdate > enddate) {
   alert('error'
}

As a string comparison

作为一个字符串比较

#1


152  

Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers

只是扩大了融合的答案。这个扩展方法使用jQuery validate插件。它将验证日期和数字。

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()) 
        || (Number(value) > Number($(params).val())); 
},'Must be greater than {0}.');

To use it:

使用它:

$("#EndDate").rules('add', { greaterThan: "#StartDate" });

or

$("form").validate({
    rules: {
        EndDate: { greaterThan: "#StartDate" }
    }
});

#2


74  

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

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

That should do it I think

我认为应该这样

#3


15  

Little late to the party but here is my part

参加聚会的时间并不晚,但这是我的部分

Date.parse(fromDate) > Date.parse(toDate)

Date.parse(fromDate)> Date.parse(迄今为止)

Here is the detail:

这是细节:

var from = $("#from").val();
var to = $("#to").val();

if(Date.parse(from) > Date.parse(to)){
   alert("Invalid Date Range");
}
else{
   alert("Valid date Range");
}

#4


14  

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.

参考jquery.validate。js和jquery-1.2.6.js。在开始日期文本框中添加一个startDate类。在结束日期文本框中添加一个endDate类。

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

希望这有助于:-)

#5


13  

I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date constructor, but others will not. For example, Chrome 18 gives

我只是在修改danteuno的答案,发现虽然出于好意,但遗憾的是,它在几个浏览器上都被破坏了。这是因为IE会对它接受的日期构造函数参数非常严格,而其他的则不会。例如,Chrome 18给出了。

> new Date("66")
  Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)

This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11") is greater than new Date("66") and this is obviously the opposite of the desired effect).

这导致代码采用“比较日期”路径,从这里开始,一切都走下坡路(例如,new Date(“11”)大于new Date(“66”),这显然与期望的效果相反)。

Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().

因此,在考虑之后,我修改了代码,使“数字”路径优先于“日期”路径,并使用JavaScript中的validate decimal numbers—IsNumeric()中提供的优秀方法验证输入确实是数字的。

In the end, the code becomes:

最后,代码变为:

$.validator.addMethod(
    "greaterThan",
    function(value, element, params) {
        var target = $(params).val();
        var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
        var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
        if (isValueNumeric && isTargetNumeric) {
            return Number(value) > Number(target);
        }

        if (!/Invalid|NaN/.test(new Date(value))) {
            return new Date(value) > new Date(target);
        }

        return false;
    },
    'Must be greater than {0}.');

#6


5  

The date values from the text fields can be fetched by jquery's .val() Method like

可以通过jquery的.val()方法获取文本字段的日期值

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 <.

我强烈建议在比较日期字符串之前先解析它们。Javascript的Date对象有一个parse()-Method,但它只支持US的日期格式(yyyyy /MM/DD)。它返回unix纪元开始后的毫秒数,因此您可以简单地将您的值与>或 <进行比较。< p>

If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.

如果您想要不同的格式(例如ISO 8661),您需要使用正则表达式或空闲日期。js库。

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:

如果你想成为超级用户狂,你可以使用jquery ui datepickers而不是textfields。有一个datepicker变体允许输入日期范围:

http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/

http://www.filamentgroup.com/lab/date_range_picker_using_jquery_ui_16_and_jquery_ui_css_framework/

#7


3  

So I needed this rule to be optional and none of the above suggestions are optional. If I call the method it is showing as required even if I set it to needing a value.

所以我需要这个规则是可选的,上面的建议都不是可选的。如果我调用这个方法,它会按需要显示,即使我将它设置为需要一个值。

This is my call:

这是我的电话:

  $("#my_form").validate({
    rules: {
      "end_date": {
        required: function(element) {return ($("#end_date").val()!="");},
        greaterStart: "#start_date"
      }
    }
  });//validate()

My addMethod is not as robust as Mike E.'s top rated answer, but I'm using the JqueryUI datepicker to force a date selection. If someone can tell me how to make sure the dates are numbers and have the method be optional that would be great, but for now this method works for me:

我的addMethod不如Mike E那么健壮。但我正在使用JqueryUI datepicker来强制选择日期。如果有人能告诉我如何确定日期是数字,并让方法是可选的,那就太好了,但是现在这个方法对我有效:

jQuery.validator.addMethod("greaterStart", function (value, element, params) {
    return this.optional(element) || new Date(value) >= new Date($(params).val());
},'Must be greater than start date.');

#8


2  

I like what Franz said, because is what I'm using :P

我喜欢弗兰兹说的,因为我用的是P。

var date_ini = new Date($('#id_date_ini').val()).getTime();
var date_end = new Date($('#id_date_end').val()).getTime();
if (isNaN(date_ini)) {
// error date_ini;
}
if (isNaN(date_end)) {
// error date_end;
}
if (date_ini > date_end) {
// do something;
}

#9


2  

$(document).ready(function(){
   $("#txtFromDate").datepicker({
        minDate: 0,
        maxDate: "+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
          $("#txtToDate").datepicker("option","minDate", selected)
        }
    });

    $("#txtToDate").datepicker({
        minDate: 0,
        maxDate:"+60D",
        numberOfMonths: 2,
        onSelect: function(selected) {
           $("#txtFromDate").datepicker("option","maxDate", selected)
        }
    });
});

Or Visit to this link

或者访问这个链接

#10


2  

In javascript/jquery most of the developer uses From & To date comparison which is string, without converting into date format. The simplest way to compare from date is greater then to date is.

在javascript/jquery中,大多数开发人员使用的是从&到日期的比较是字符串,没有转换成日期格式。最简单的比较日期的方法是更大的日期。

Date.parse(fromDate) > Date.parse(toDate)

Always parse from and to date before comparison to get accurate results

在进行比较之前,始终要对数据进行解析,以得到准确的结果

#11


1  

function endDate(){
    $.validator.addMethod("endDate", function(value, element) {
      var params = '.startDate';
        if($(element).parent().parent().find(params).val()!=''){
           if (!/Invalid|NaN/.test(new Date(value))) {
               return new Date(value) > new Date($(element).parent().parent().find(params).val());
            }
       return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) > parseFloat($(element).parent().parent().find(params).val())) || value == "";              
      }else{
        return true;
      }
      },jQuery.format('must be greater than start date'));

}

function startDate(){
            $.validator.addMethod("startDate", function(value, element) {
            var params = '.endDate';
            if($(element).parent().parent().parent().find(params).val()!=''){
                 if (!/Invalid|NaN/.test(new Date(value))) {
                  return new Date(value) < new Date($(element).parent().parent().parent().find(params).val());
            }
           return isNaN(value) && isNaN($(element).parent().parent().find(params).val()) || (parseFloat(value) < parseFloat($(element).parent().parent().find(params).val())) || value == "";
                 }
                        else{
                     return true;
}

    }, jQuery.format('must be less than end date'));
}

Hope this will help :)

希望这能有所帮助。

#12


1  

jQuery('#from_date').on('change', function(){
    var date = $(this).val();
    jQuery('#to_date').datetimepicker({minDate: date});  
});

#13


-2  

If the format is guaranteed to be correct YYYY/MM/DD and exactly the same between the two fields then you can use:

如果格式保证是正确的yyyyy /MM/DD,并且两个字段之间的格式完全相同,那么您可以使用:

if (startdate > enddate) {
   alert('error'
}

As a string comparison

作为一个字符串比较