2010-02-16 149 views
1

我有一个Web应用程序,在这我必须验证一个日期字段的格式,如mm/dd/yyyy。我在网上搜索,但我没有得到适当的。请通过提供新功能或纠正我的代码来帮助我。我的代码如下所示。我已经叫这个在onblur事件的JS函数..验证的日期

function isValidDate() { 

var re = new RegExp('^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(19|20)dd$'); 

if (form1.txtDateOfOccurance.value != '' && !form1.txtDateOfOccurance.value.match(re)) { 
    alert("Invalid date format: " + form1.txtDateOfOccurance.value); 
    form1.txtDateOfOccurance.value = ""; 
    form1.txtDateOfOccurance.focus(); 
    isEnable(); 
    return false; 
} 

}提前

谢谢..

回答

0

我只是尝试解析字符串作为Date对象,并将检查结果(假设你只需要知道它是否是一个有效的日期或没有):

var myDate = Date.parse(form1.txtDateOfOccurance.value); 
if(isNaN(myDate)){ 
    // it's not a real date 
} 
+3

不好。仅仅因为一个字符串生成有效的日期并不意味着它是一个有效的日期开始。例如2011/2/31将被称为无效日期,但在提供给'new Date()'时,它会给出2011年3月3日。因此无效的日期字符串可以生成有效的日期对象。 – RobG

0
function IsValidDate(str) { 
    var str2=""; 
    var date = new Date(str); 
    str2 = (date.getMonth()+1) + "/" 
       + date.getDay() + "/" 
       + (date.getYear()+1900); 

    return (str == str2); 
} 
1

这是你想要的正则表达式。


var re = /^(0[1-9]|1[0-2])\/(0[1-9]|[1-3]\d)\/((19|20)\d\d)$/ 

虽然你可能会更好过,因为inkedmn建议通过解析输入,因为MM/DD/YYYY是通过Date.parse公认的日期格式验证。

+0

Just being anal:'var re =/^(0 [1-9] | 1 [0-2])\ /(0 [1-9] | [1-2] \ d | 3 [0-1] )\ /((19 | 20)\ d \ d)$ /'。您将接受1/39/2011作为日期。 – danyim

0

您可以使用:

function checkdate(input){ 
var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity 
var returnval=false; 
if (!validformat.test(input.value)) 
alert("Invalid Date Format. Please correct and submit again."); 
else{ //Detailed check for valid date ranges 
var monthfield=input.value.split("/")[0]; 
var dayfield=input.value.split("/")[1]; 
var yearfield=input.value.split("/")[2]; 
var dayobj = new Date(yearfield, monthfield-1, dayfield); 
if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)) 
alert("Invalid Day, Month, or Year range detected. Please correct and submit again."); 
else 
returnval=true; 
} 
if (returnval==false) input.select() 
return returnval; 
} 
0

这是我的实现。它检查一个有效的范围和一切。

function validateDate(g) { 
    var reg = new RegExp("^(([0-9]{2}|[0-9])/){2}[0-9]{4}$"); 
    // Checks if it fits the pattern of ##/##/#### regardless of number 
    if (!reg.test(g)) return false; 
    // Splits the date into month, day, and year using/as the delimiter 
    var spl = g.split("/"); 
    // Check the month range 
    if (parseInt(spl[0]) < 1 || parseInt(spl[0]) > 12) return false; 
    // Check the day range 
    if (parseInt(spl[1]) < 1 || parseInt(spl[1]) > 31) return false; 
    // Check the year range.. sorry we're only spanning ten centuries! 
    if (parseInt(spl[2]) < 1800 || parseInt(spl[2]) > 2800) return false; 
    // Everything checks out if the code reached this point 
    return true; 
}