Credit Card Validation with JavaScript and Regular Expressions

Continuing from the last post, for the javascript I checked the credit card number of form submittal, (along with a lot other things, like required fields, correct phone numbers, etc… ) and if it isn’t correct, throw an alert and prevent the form from submitting (Ignore the PHP tags, haven't gotten around to adding a generic code highlighting plug yet...). [php] var ccType = document.getElementById('credit_card').value; switch(ccType) { case 'AMEX': var goodCC = /^3[47]{1}[0-9]{13}$/; break; case 'Visa': var goodCC = /^4[0-9]{15}$/; break; case 'Mastercard': var goodCC = /^5[1-5]{1}[0-9]{14}$/; break; case 'Discover': var goodCC = /^6011[0-9]{12}$/; break; default: var goodCC = /^[0-9]{15,16}$/; } if(!goodCC.test(ccNum)) { problem += "Please enter in a valid credit card number (only use numbers)\n"; } } if (problem != ‘’) { alert(problem); //code to stop the form from submitting } [/php]

Posted In: JavaScript, regular expressions

Commentary