user3310635 user3310635 - 4 years ago 116
HTML Question

Credit card expiry date validation in HTML

HTML code:

<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 code:

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;
}
}


These codes are basically used to validate the expiry date for credit card.For example,if today is March 2014 and the user chooses February 2014,I want the form to return false.However,if he chooses April 2014,I want the form to return true and proceed to the next page.If there are mistakes,can you please point them out and do a simple explanation?

Answer Source

You should update values from select-boxes every time user changes values, please see this fiddle 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...

}

}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download