JavaScript判断两种格式的输入日期的正确性的代码
2024-09-06 12:42:49
供稿:网友
最简单的
代码如下:
function isValidDate(dateStr) {
var matchArray = dateStr.match(/^[0-9]+-[0-1][0-9]-[0-3][0-9]$/)
if (matchArray == null) {
alert("Invalid date: " + dateStr);
return false;
}
return true;
}
function isValidDate(dateStr) {
var matchArray = dateStr.match(/^[0-9]+-[0-1][0-9]-[0-3][0-9]$/)
if (matchArray == null) {
alert("Invalid date: " + dateStr);
return false;
}
return true;
}
第二种
代码如下:
<script language=javascript>
String.prototype.isDate = function()
{
var r = this.match(/^(/d{1,4})(-|//)(/d{1,2})/2(/d{1,2})$/);
if(r==null)return false; var d = new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
alert("2002-01-31".isDate());
alert("2002-01-41".isDate());
</script>
<script language=javascript>
String.prototype.isDate = function()
{
var r = this.match(/^(/d{1,4})(-|//)(/d{1,2})/2(/d{1,2})$/);
if(r==null)return false; var d = new Date(r[1], r[3]-1, r[4]);
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
alert("2002-01-31".isDate());
alert("2002-01-41".isDate());
</script>
第三种,比较复杂的
代码如下:
<script language=javascript>