使用日期对象的JavaScript日期验证 [英] javascript date validation using date object
问题描述
根据 http://www.codingforums.com/archive/ index.php / t-98569.html ,可以使用javascript的日期对象来完成日期验证。
According to http://www.codingforums.com/archive/index.php/t-98569.html, the date validation could be done using the javascript's date object.
我有一个类似的场景,我有个别的年份,月份,日期在单独的文本框中,通过正则表达式验证。现在我想利用JS的日期对象检查一个月的日子和闰年验证,这些都不是由RegExp验证完成的。但上述链接讨论的内容对我而言并不奏效。
例如,
I've a similar scenario, where I have individual year,month,date in seperate text boxes which get validated by regular expressions.Now I would like to leverage the JS's date object to check stuff like days in a month and leap year validation which are not done by RegExp validation. But the stuff discussed in the above link doesn't quite work for me. For example,
<script type="text/javascript">
var dy= new Date(2001,2,30);
alert(dy.getFullYear()+" "+dy.getMonth()+" "+dy.getDate());
</script>
返回日期。 dy.getMonth()不应该返回一个像-1这样的表示30天在二月份不存在?如果这是不可能使用Date对象,请建议一些替代方法验证日期。
returns the date as it is. Shouldn't dy.getMonth() return something like -1 to show that 30 days doesn't exist in the month of February?. If this isn't possible using Date object, please suggest some alternatives to validate the date.
更新:
我刚刚发现另一个链接(http:// internotredici.com/article/checkdateinjavascript/)说同样的。
PS:我正在JS1.2上工作,这是相当老的。
Update: I just found another link(http://internotredici.com/article/checkdateinjavascript/) which says the same. PS:I am working on JS1.2 which is pretty old.
推荐答案
你可以从日期,月份,年份,然后检查这些位是否正确。
You can make the date from the day, month, year bits, and then check that the bits are correct.
function isvalid_mdy(s){
var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
A[0]-=1;
try{
day= new Date(A[2], A[0], A[1]);
if(day.getMonth()== A[0] && day.getDate()== A[1]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
function isvalid_dmy(s){
var day, A= s.split(/\D+/).map(function(itm,i){return parseInt(itm,10)});
A[1]-=1;
try{
day= new Date(A[2], A[1], A[0]);
if(day.getMonth()== A[1] && day.getDate()== A[0]) return day;
throw new Error('Bad Date ');
}
catch(er){
return er.message;
}
}
这篇关于使用日期对象的JavaScript日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!