2014-03-29 42 views
0

HTML代碼:信用卡到期日在驗證HTML

<tr> 
    <td><label for="expiry_day">Expiry date(MM/YYYY):<span id="imp">*</span></label></td> 
    <td> 
    <select id="expiry_month" tabindex="4"> 
    <optgroup label="Month"> 
    <option value="01">January</option> 
    <option value="02">February</option> 
    <option value="03">March</option> 
    <option value="04">April</option> 
    <option value="05">May</option> 
    <option value="06">June</option> 
    <option value="07">July</option> 
    <option value="08">August</option> 
    <option value="09">September</option> 
    <option value="10">October</option> 
    <option value="11">November</option> 
    <option value="12">December</option> 
    </optgroup> 
    </select> 

    <select id="expiry_year" tabindex="5"> 
    <optgroup label="Year"> 
    <script>generate_year();</script> 
    </optgroup> 
    </select> 
    </td> 
</tr> 

JavaScript代碼:

function generate_year()     /*For generate cc year*/ 
    { 
     for (var i = 2014; i <= 2104; i++) 

     { 
      document.write ("<option value='" + i + "'>" + i + "</option>"); 
     } 
    } 

     function val_cc() {   

     var expiry_month = document.getElementById("expiry_month").value; 
     var expiry_year = document.getElementById("expiry_year").value; 
     var today = new Date(); 
     var expiry_date = today.setFullYear(expiry_year, expiry_month); 

     if (today.getTime() > expiry_date.getTime()) 

     { 
      alert ("\u2022Expiry month and year cannot be blank/Expiry month and year is before today month and year."); 

      return false; 
     } 
} 

這些代碼主要用於驗證信用card.For例如到期日,如果今天是2014年3月,用戶選擇2014年2月,我希望表單返回false。但是,如果他選擇2014年4月,我希望表單返回true並進入下一頁。如果有錯誤,請指出它們並做一個簡單的解釋?

+0

其中是驗證功能?把你的驗證碼放在一個函數中 –

+0

對不起,這是我的錯誤,並進行了更正。 – user3310635

+0

你的程序中的expiry_date在哪裏 –

回答

1

您應該更新從選擇盒值每個用戶更改值時,請參閱此琴http://jsfiddle.net/shershen08/wcFC4/

function runMyCheck(){ 
//update value every run 
var expiry_month = document.getElementById("expiry_month").value; 
var expiry_year = document.getElementById("expiry_year").value; 

var today = new Date(); 
var selDate = new Date(); 

if (today.getTime() > selDate.setFullYear(expiry_year, expiry_month)){ 
//too late 
    alert ("\u2022Expiry month and year cannot be blank/Expiry month and year is before today month and year."); 
    return false; 
} else { 
//do good stuff... 

} 

}

+0

其實我的代碼有什麼問題?因爲我的代碼與你的代碼很相似。如果我希望在用戶點擊'submit'後出現錯誤消息,怎麼辦? – user3310635

+0

然後你可以添加處理程序給你從標籤 -

,而不是使用