I’m implementing a credit card expiry date validation whereby the months and years are in separate dropdowns; it’s almost there, except for one small layout issue.
The HTML looks like this:
<form id="myform">
<table>
<tr>
<th colspan="2"><label class="secure-section-title" for="ccexp">Expiration date</label></th>
</tr>
<tr>
<td><select id="ccexp" name="cc_exp_month" class="required creditcardexpiry">
<option value="01">01</option> ... <option value="12">12</option>
</select> / <select name="cc_exp_year" class="required creditcardexpiry">
<option value="2012">12</option> ... <option value="2021">21</option>
</select></td>
<td></td>
</tr>
</table>
</form>
The JavaScript that performs the validation is here:
$('#myform').validate({
errorPlacement: function(error, element) {
element
.closest('tr') // take closest parent
.prev('tr')
.find('> th')
.append(error)
},
groups: {
creditcardexpiry: 'cc_exp_month cc_exp_year'
}
});
$.validator
.addMethod('creditcardexpiry', function(value, element) {
var form = element.form,
expiry = form['cc_exp_year'].value + form['cc_exp_month'].value,
date = new Date(),
month = date.getMonth() + 1,
now = '' + date.getFullYear() + (month < 10 ? '0' + month : month);
return expiry > now;
});
It basically validates only if the expiry date is one month in the future (the maximum of 10 years in the future is limited by the dropdowns).
The problem scenario is this:
-
Enter a date in the past; the error message will show and the dropdown is red
-
Fix the error by increasing the year to 2014; the error message disappears
The problem is that the months dropdown is still red until clicked again! The fields are grouped, so I expected that both dropdowns get cleared when the invalid entry is resolved.
Am I overlooking something obvious here or is this a bug?
Update
It’s not really a bug regarding the groups property, because that just makes sure errors in both fields don’t cause two messages.
Apparently, a dropdown is revalidated by triggering a click event on it (by default). So my solution is to trigger clicks between the two dropdowns when their selected value changes.
I’m not very pleased with this fix, so I’m hoping someone else can come up with something better.
Demo