我有3个下拉框来显示开始日期(日/月/年)。我还有3个要显示结束日期。
我希望验证
我真的很挣扎,并希望有人可以帮助我作为一个相对初学者。
到目前为止我的代码如下:
<script type="text/javascript">
var monthtext=["01","02","03","04","05","06","07","08","09","10","11","12"];
function populatedropdown(dayfield, monthfield, yearfield){
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<=31; i++)
dayfield.options[i]=new Option(i, i)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=today.getFullYear()
for (var y=0; y<4; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
HTML:
<label>Start date :</label>
<select name="startDateDay" id="startDaydropdown"></select>
<select name="startDateMonth" id="startMonthdropdown"></select>
<select name="startDateYear" id="startYeardropdown"></select>
<label>End date :</label>
<select name="endDateDay" id="endDaydropdown"></select>
<select name="endDateMonth" id="endMonthdropdown"></select>
<select name="endDateYear" id="endYeardropdown"></select>
答案 0 :(得分:0)
为什么不只有两个文本字段让用户输入日期,然后让new Date(textfield.value)
进行繁重的日期验证?
然后您只需要担心确定日期在7天之内。您可以使用Date object轻松地完成该部分,也许可以使用以下简单的内容:
var dateDiff = date2.getTime() - date1.getTime();
if(dateDiff <= 1000*60*60*24*7 && dateDiff > 0) {
return 'valid';
} else {
return 'invalid';
}
如果将此作为提交按钮的一部分运行,您的代码将类似于:
function validateDatesOnSubmit() {
var date1 = new Date(document.getElementById('startDate').value);
var date2 = new Date(document.getElementById('endDate').value);
if(date1 == "Invalid Date" || date2 == "Invalid Date") {
alert("You have entered an invalid date, please fix this.");
return false;
}
var dateDiff = date2.getTime() - date1.getTime();
if(dateDiff <= 1000*60*60*24*7 && dateDiff >= 0) {
return true;
} else {
alert("You have entered a range beyond one week, please reduce the number of days selected.");
return false;
}
}
document.getElementById('myForm').onsubmit = validateDatesOnSubmit;
答案 1 :(得分:-1)
假设日期的格式为dd-mm-yyyy
或dd/mm/yyyy
,则为:
function toDate(t) {
var t = t.split(/[-\/]/g);
return new Date(t[2],t[1] - 1, t[0]);
}
function within7Days(t0, t1) {
var d0 = toDate(t0);
var d1 = toDate(t1);
return d0.setDate(d0.getDate() + 7) > d1;
}
alert(within7Days('12-3/2012', '18/3/2012')); // true
alert(within7Days('12-3/2012', '19/3/2012')); // false
如果日期可以在之前或之后,您可能需要使用Math.abs()
顺便说一下,不信任Date.parse
。在ECMA-262第3版中,它基本上依赖于实现。在ES5中,它被指定为首先尝试将字符串解析为ISO8601,但在此之后,它是实现特定的。 IE(至少<9)将无法正确解析ISO8601日期字符串。
在任何情况下,手动解析日期都是微不足道的。