Skip to content

Instantly share code, notes, and snippets.

@hartct
Created December 27, 2010 16:16
Show Gist options
  • Save hartct/756256 to your computer and use it in GitHub Desktop.
Save hartct/756256 to your computer and use it in GitHub Desktop.
JavaScript function for validating subscription information - assumes certain form input IDs for name,adress, CVV, card number.
function cardval() {
// validate presence of first name, last name, billing address and CVV.
if ($("#subscription_first_name").val().length == 0 || $("#subscription_last_name").val().length == 0 || $("#subscription_address").val().length == 0 || $("#subscription_city").val().length == 0 || $("#subscription_state").val().length == 0 || $("#subscription_zipcode").val().length == 0 || $("#subscription_cvv2").val().length == 0) {
alert("All fields on the form must be filled out. Please complete the form and try again.");
return false;
}
// check CVV2 is 3 or 4 digits
var re = new RegExp(/^\d{3,4}$/);
if ($("#subscription_cvv2").val().match(re)==null) { //if match failed
alert("CVV must be a three or four digit number.");
return false;
}
// remove non-numerics from card number
var s = $("#subscription_card").val();
var v = "0123456789";
var w = "";
for (i=0; i < s.length; i++) {
x = s.charAt(i);
if (v.indexOf(x,0) != -1)
w += x;
}
// validate number
j = w.length / 2;
if (j < 6.5 || j > 8 || j == 7) {
alert("The card number you've entered is not valid. Please check the number and try again.");
return false;
}
k = Math.floor(j);
m = Math.ceil(j) - k;
c = 0;
for (i=0; i<k; i++) {
a = w.charAt(i*2+m) * 2;
c += a > 9 ? Math.floor(a/10 + a%10) : a;
}
for (i=0; i<k+m; i++) c += w.charAt(i*2+1-m) * 1;
if (c%10 == 0) {
return true;
} else {
alert("The card number you've entered is not valid. Please check the number and try again.");
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment