2010-10-06 111 views
0

我正在檢查MM/DD/YYYY。javascript月份和日期和年份檢查

當您輸入0/0/0或00/00/0000時,我的腳本將失敗。我正在嘗試檢查用戶是否已超過21歲,並且必須輸入有效的兩位數月份,兩位數日期和四位數字年份。

有什麼建議嗎?

$("#gate-box").submit(function() { 

    var day = $("#day").val(); 
    var month = $("#month").val(); 
    var year = $("#year").val(); 

    var age = 21; 

    var mydate = new Date(); 
    mydate.setFullYear(year, month - 1, day); 

    var currdate = new Date(); 
    currdate.setFullYear(currdate.getFullYear() - age); 
    if ((currdate - mydate) < 0) {   
     $.msg("Sorry, you must be at least " + age + " to enter."); 
     return false; 
    } 
    else if (month > 12) { 
     $('#month').css({ 'border': '1px solid red' }); 
     $.msg("Please enter a valid month."); 
     $('#month').focus(); 
     return false; 
    } 
    else if (day > 31) { 
     $('#month').css({ 'border': 'none' }); 
     $('#day').css({ 'border': '1px solid red' }); 
     $.msg("Please enter a valid day."); 
     $('#day').focus(); 
     return false; 
    } 
    else if (month.length === 0 || day.length === 0 || year.length === 0) { 
     $('#day').css({ 'border': 'none' }); 
     $.msg("Please enter all fields."); 
     return false; 
    } 

    if ((currdate - mydate) > 0) { 
     $.colorbox.close() 
     $.setCookie('diageoagecheck', 'verified', { duration: 3 }); 
    } 
    return false; 
}); 
+0

嘗試驗證**之前的輸入**使用它們來創建日期對象。 – 2010-10-06 20:15:48

+0

如何檢查兩位數月份,兩位數日期和四位數年份。當您輸入0/0/0或00/00/0000時,腳本目前失敗。 – user244394 2010-10-06 20:26:33

+0

檢查它們是否落入(1-31),(1-12),(1900-2100) – 2010-10-06 20:37:21

回答

4

你應該使用下面的方法來驗證,如果輸入的是確實的數字,然後檢查

Validate numbers in JavaScript - IsNumeric()

function IsNumeric(input) 
{ 
    return (input - 0) == input && input.length > 0; 
} 

複製的範圍和閱讀後使用它像這樣(輸入

if (!IsNumeric(day) || day < 1) 
    {/*handle wrong day here and return false*/} 
if (!IsNumeric(month) || (month < 1) || (month > 12)) 
    {/*handle wrong month here and return false*/} 
if (!IsNumeric(year) || (year < 1900) || (year > 2100)) 
    {/*handle wrong year here and return false*/} 

var lastDayOfMonth = new Date(year, parseInt(month) + 1, -1).getDate(); 
if (day > lastDayOfMonth) { 
    {/*handle wrong year here and return false*/} 
} 
+0

的可接受範圍內。這不會使用正確的日曆並檢查一個月中的日期。 – 2017-06-10 23:53:16

+0

@TimothyGonzalez OP特別要求自己驗證每個字段。 – 2017-06-10 23:59:09

+1

也許OP是錯誤地問錯了問題。如果你正在處理日期,你不能逃避這些字段是相關的。它沒有回答這個問題的意圖,即確定年齡。如果我出生於2017年4月31日(2017年4月31日不存在的日期),我多大了? – 2017-06-11 00:04:48