2010-02-16 148 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; 
}