Dear gurus,
I have a credit card script that should check for the card type and determine that a user entered correct value for the card.
For instance, Master card, Visa and Discover have 16 digits.
I am trying to ensure that if a user enters less than 16 digitis, there should be an error flag.
Similarly, if a user enters more than the required digits, he or she should be flagged.
So far, as long as the card is up to 15 digits, it is processed.
Please take a look and advise.
Thanks in advance.
[code]
<SCRIPT LANGUAGE=javascript>
<!–
// Client script validates form field entries for credit card
function validate(theForm)
{
if(document.cform.IsHidden.value==”false”)
{
if (theForm.cardname.value == “” || theForm.cardname.value.length < 2)
{
alert(“Please fill in the name found on your credit card.”);
theForm.cardname.focus() ;
return false;
}
if ((theForm.paymentm = “Visa” || theForm.paymentm = “Disc” || theForm.paymentm = “MC” ) AND (theForm.cardno.value == “” || theForm.cardno.value.length < 16 || theForm.cardno.value == “0000-0000-0000-0000”)
{
alert(“Please fill in the card number in this format: 0000-0000-0000-0000.”);
theForm.cardno.focus();
return false;
}
return true;
}
}
function isValidCreditCard(type, ccnum) {
if (type == “Visa”) {
// Visa: length 16, prefix 4, dashes optional.
var re = /^4d{3}-?d{4}-?d{4}-?d{4}$/;
} else if (type == “MC”) {
// Mastercard: length 16, prefix 51-55, dashes optional.
var re = /^5[1-5]d{2}-?d{4}-?d{4}-?d{4}$/;
} else if (type == “Disc”) {
// Discover: length 16, prefix 6011, dashes optional.
var re = /^6011-?d{4}-?d{4}-?d{4}$/;
} else if (type == “AmEx”) {
// American Express: length 15, prefix 34 or 37.
var re = /^3[4,7]d{13}$/;
} else if (type == “Diners”) {
// Diners: length 14, prefix 30, 36, or 38.
var re = /^3[0,6,8]d{12}$/;
}
if (!re.test(ccnum)) return false;
// Checksum (“Mod 10”)
// Add even digits in even length strings or odd digits in odd length strings.
var checksum = 0;
for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
checksum += parseInt(ccnum.charAt(i-1));
}
// Analyze odd digits in even length strings or even digits in odd length strings.
for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
var digit = parseInt(ccnum.charAt(i-1)) * 2;
if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
}
if ((checksum % 10) == 0) return true; else return false;
}
</script>
Then I will invoke it here:
[code]
<td width=”350″>
<select name=”paymentm” onChange=”isValidCreditCard(this)”>
<option value=”Disc”>Discover</option>
<option selected value=”Visa”>Visa</option>
<option value=”AmEx”>American Express</option>
<option value=”MC”>Mastercard</option>
<option value=”Diners”>Diner’s Club</option>
</select>
</td>