$( document ).ready(function() { $( "#card_details" ).submit(function( event ) { return validate_card_details_form(); }); }); function validate_card_details_form() { var valid = true; if ($("#chname").val() == "") { $( "#chname").next().html("You must put the cardholder name"); valid = false; } else $( "#chname").next().html(''); if ($("#expiry_month").val() == "" || $("#expiry_year").val() == "") { $( "#expiry").next().html("You must select an expiry date"); valid = false; } else $( "#expiry").next().html(''); if ($("#card_type").val() == "") { $( "#card_type").next().html("You must select a card type"); valid = false; } else $( "#card_type").next().html(''); if ($("#cardnumber").val() == "") { $( "#cardnumber").next().html("You must put a card card number"); valid = false; } else if (!valid_credit_card($("#cardnumber").val())) { $( "#cardnumber").next().html("The card number is invalid"); valid = false; } else $( "#cardnumber").next().html(''); return valid; } function valid_credit_card(value) { // accept only digits, dashes or spaces if (/[^0-9-\s]+/.test(value)) return false; // The Luhn Algorithm. It's so pretty. var nCheck = 0, nDigit = 0, bEven = false; value = value.replace(/\D/g, ""); for (var n = value.length - 1; n >= 0; n--) { var cDigit = value.charAt(n), nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = !bEven; } return (nCheck % 10) == 0; }