How do I validate a credit card exp date (2 fields) with livevalidation

1k Views Asked by At

using http://livevalidation.com on a custom PHP donation page. I want to make credit card exp dates in the past invalid, but all other selections valid. I'm using two select fields for the month and year.

Seems like this should be done with the validate.custom or validate.now functions, but there are no good examples in the documentation on these. Can't seem to get them to work...

<select tabindex="4" id="exp_month" name="exp_month">
  <option value="01">01</option>
  <option value="02">02</option>
  <option value="03">03</option>
  <option value="04">04</option>
  <option value="05">05</option>
  <option value="06">06</option>
  <option value="07">07</option>
  <option value="08">08</option>
  <option value="09">09</option>
  <option value="10">10</option>
  <option value="11">11</option>
  <option value="12">12</option>
</select>

<select tabindex="5" id="exp_year" name="exp_year">
  <option value="11">2011</option>
  <option value="12">2012</option>
  <option value="13">2013</option>
  <option value="14">2014</option>
  <!-- etc -->
</select>

<script>
  var exp_year = new LiveValidation( "exp_year", { validMessage: " ", failureMessage: "Enter a valid exp date", onlyOnSubmit: true } );
  exp_year.add( Validate.Custom( 
  //  ????    
  );
</script> 
2

There are 2 best solutions below

0
On

ok - I finally figured it out... using a bit of php in there and grabbing the current value of month...

var exp_year = new LiveValidation( "exp_year", { validMessage: " ", failureMessage: "Enter a valid exp date", onlyOnSubmit: true } );
exp_year.add( Validate.Custom, { against: function(value){
    var currentyymm=<?php print date(ym) ?>;
    var expmo1=document.getElementById("exp_month").selectedIndex;
    var expmo2=document.getElementById("exp_month").options;
    if  (value+expmo2[expmo1].value >= currentyymm) { return true; }
    else { return false; }
}, failureMessage: "Enter a valid exp date" } ); 
0
On

If you trust the user's system clock, then something like:

var d = new Date();
var y0 = d.getFullYear();
var m0 = d.getMonth() + 1;
var y1 = document.getElementById('exp_year').value;
var m1 = document.getElementById('exp_month').value;

if (y0 == y1 && m0 < m1) {
  // selected date is in the past
}

Otherwise, pass the month and year from the server (say in hidden inputs) and test against those.