使用 jQuery 验证结束日期是否大于开始日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/833997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validate that end date is greater than start date with jQuery
提问by input
How do I check/validate in jQuery whether end date [textbox] is greater than start date [textbox]?
如何在 jQuery 中检查/验证结束日期 [textbox] 是否大于开始日期 [textbox]?
回答by Mike E.
Just expanding off fusions answer. this extension method works using the jQuery validate plugin. It will validate dates and numbers
只是扩展融合答案。此扩展方法使用 jQuery 验证插件工作。它将验证日期和数字
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" }
}
});
回答by Shane O'Grady
var startDate = new Date($('#startDate').val());
var endDate = new Date($('#endDate').val());
if (startDate < endDate){
// Do something
}
That should do it I think
我认为应该这样做
回答by Kamran Ahmed
Little late to the party but here is my part
聚会有点晚,但这是我的部分
Date.parse(fromDate) > Date.parse(toDate)
Date.parse(fromDate) > Date.parse(toDate)
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");
}
回答by Russell Giddings
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 :-)
希望这可以帮助 :-)
回答by Jon
I was just tinkering with danteuno's answerand found that while good-intentioned, sadly it's broken on several browsers that are notIE. 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 的浏览器上被破坏了。这是因为 IE 对它接受什么作为Date
构造函数的参数非常严格,但其他人则不会。例如,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中验证十进制数字 - 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}.');
回答by Franz
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,但它只支持美国日期格式 (YYYY/MM/DD)。它返回自 unix 纪元开始以来的毫秒数,因此您可以简单地将您的值与 > 或 < 进行比较。
If you want different formats (e.g. ISO 8661), you need to resort to regular expressions or the free date.js library.
如果您想要不同的格式(例如 ISO 8661),您需要求助于正则表达式或免费的 date.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。有一个允许输入日期范围的日期选择器变体:
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/
回答by Charity
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 日期选择器来强制选择日期。如果有人能告诉我如何确保日期是数字并且该方法是可选的,那就太好了,但现在这种方法对我有用:
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.');
回答by Kunal Brahme
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 中,大多数开发人员使用字符串的 From & To 日期比较,而不转换为日期格式。从日期进行比较的最简单方法是大于日期。
Date.parse(fromDate) > Date.parse(toDate)
Always parse from and to date before comparison to get accurate results
在比较之前总是从和到现在进行解析以获得准确的结果
回答by saggy
$(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
或访问此链接
回答by Atchyut Nagabhairava
jQuery('#from_date').on('change', function(){
var date = $(this).val();
jQuery('#to_date').datetimepicker({minDate: date});
});