/    Sign up×
Community /Pin to ProfileBookmark

Credit card validation issues

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>
[/code]

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>
[/code]

to post a comment
JavaScript

26 Comments(s)

Copy linkTweet thisAlerts:
@age13kidDec 03.2004 — you really dont need all that code but for mininmal length you might need some
<i>
</i>&lt;input type=text MAXLENGTH="16" name="credit"&gt;
Copy linkTweet thisAlerts:
@96turnerriDec 03.2004 — for CC validation you should not just be using JavaScript you should be doing this server-side aswell due to the importance of this validation (just incase you are not i thought id post it)
Copy linkTweet thisAlerts:
@Warren86Dec 03.2004 — I don't see where the validate() function is called. But, nevertheless, I'm assuming, because of the comments within that function, that the user is REQUIRED to input dashes between the credit card number segments. Therefore, maybe you could try this:

function isValidCreditCard(type, ccnum) {

validLength = true;

if (type == "Visa") {

// Visa: length 16, prefix 4, dashes optional.

if (ccnum != 19){validLength = false} //using 16 plus 3 dashes

var re = /^4d{3}-?d{4}-?d{4}-?d{4}$/;

}

....

Then at the end of the function...

if ((checksum % 10) == 0) return true;

if (!validLength) return false;

else return false;
Copy linkTweet thisAlerts:
@janiceauthorDec 03.2004 — hi all and thanks for your response.

Warren,

what is the difference between what you suggested and what I posted?

The only difference I see is the ValidLength=True

age13kid, your synyax says if you typed the 16th character or digit, you *can't* type anything else.

What happens if you type 15, instead of 16?


96turnerri, I know that this is very crucial to protecting user's credit card.

The social security is integrated with ASP.

Infact once everything is working now, I will save the javascript as a .js file and use it as in include file.

I just want to make sure everything is working first.
Copy linkTweet thisAlerts:
@Warren86Dec 03.2004 — Yes. My error. I omitted the length method.

validLength creates a new local boolean variable and sets it to true.

Try it like this:

if (ccnum.length != 19){}

I added a length test, which could be repeated, with the appropriate parameter for each credit card type. Each "else" section tests the length of the ccnum string, including dashes, if not equal to the specified length, the validLength variable is set to false.

The line must not have been obvious, within the code.

Then, at the bottom of the function, I added a test for the validLength boolean variable. If it's not true, then return is false.

if (ccnum.length != 19){validLength = false} //using 16 plus 3 dashes


.....

if (!validLength) return false;
Copy linkTweet thisAlerts:
@Warren86Dec 03.2004 — Please note that I edited the above post several times. I see that you are now online.
Copy linkTweet thisAlerts:
@janiceauthorDec 03.2004 — hi Warren,

There is definitely something going on with this code.

After making your changes, it is still not working.

This is the original code that works with just one validation rule.

This one says that as long as the credit card number is not less than 15, accept it.

This is not sufficient for ecommerce credit card transaction.

Take a look at this.

Will it be easier to modify this one?

<i>
</i>&lt;SCRIPT LANGUAGE=javascript&gt;
&lt;!--
// 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 &lt; 2)
{
alert("Please fill in the name found on your credit card.");
theForm.cardname.focus();
return false;
}
if (theForm.cardno.value == "" || theForm.cardno.value.length &lt; 15 || 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 CheckPayment(Object)
{
var payment

<i> </i> payment = Object.options[Object.selectedIndex].value;

<i> </i> if((payment=="Checks" || payment=="Money Order"))
<i> </i> {
<i> </i> document.getElementById("Show_1").style.display="none";
<i> </i> document.cform.IsHidden.value="true"
<i> </i> }
<i> </i> else
<i> </i> {
<i> </i> document.getElementById("Show_1").style.display="";
<i> </i> document.cform.IsHidden.value="false"
<i> </i> }
<i> </i>}
//--&gt;
&lt;/script&gt;
Copy linkTweet thisAlerts:
@Warren86Dec 03.2004 — The only thing that presents itself is the number 15, in this line:


(theForm.cardno.value == "" || theForm.cardno.value.length < 15 || theForm.cardno.value == "0000-0000-0000-0000")

And, looking at it, a test is being performed for an entry of 4 sets of 4 zeros, plus 3 dashes.

You might try eliminating this length test, because in my previous post, I provided a lenght test for each type of credit card.

Try editing the above line of code to this:

(theForm.cardno.value == "" || theForm.cardno.value == "0000-0000-0000-0000")

,eliminating the test for less than 15 characters, which, obviously isn't applicable to all card types.
Copy linkTweet thisAlerts:
@janiceauthorDec 03.2004 — what if it is less than 16?

Should I protect against that?
Copy linkTweet thisAlerts:
@Warren86Dec 03.2004 — I'm having difficulty communicating with you. I repeat, that the code I intially posted, after correcting it, of course, provides a lenght test for EACH type of credit card.

For example, a Visa credit card number, with the included dashes, MUST be 19 characters in length.


This is the CORRECTED segement of the code.

function isValidCreditCard(type, ccnum) {

validLength = true;

if (type == "Visa") {

// Visa: length 16, prefix 4, dashes optional.

if (ccnum.length != 19){validLength = false} //using 16 plus 3 dashes

var re = /^4d{3}-?d{4}-?d{4}-?d{4}$/;

}

You can insert a similar test in each "else" section, for each credit card type.

For example, American Express:

else if (type == "AmEx") {

// American Express: length 15, prefix 34 or 37.

if (ccnum.length != 15){validLength = false}

var re = /^3[4,7]d{13}$/;

}

Do you follow?
Copy linkTweet thisAlerts:
@Warren86Dec 03.2004 — Just in case, again, I edited the above post. It's not this:

ccnum,length

It's this:

ccnum.length
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — hi Warren,

Sorry I was forced to leave abruptly.

Yes, I am following what you are trying to tell and no, we are not having difficulty communicating.

The only I am trying to make is that I have used your most recent version of the code but it is *still* not working.

What I mean by not working is that the code is *not* performing the necessary checks.

For instance, if I select MC as payment type, and I enter 15 digits, I would like to get some error that tells me that MC (Mastercard) must be 16 digits.

So far, it doesn't matter what I enter, as long as the digits are up to 15, the card is processed.

That's all I am trying to say.
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — I made all the changes we discussed, and I eliminated all the subsequent "else" statements. A series of "if" tests should work. "if" else should not be necessary. The separate lenght test for each cc type is increased by the number of dashes the user is required to input. Meaning, 16 credit card digits, plus 3 dashes, and the length should be 19.

I also saw the word AND being used in the first function. It should be &&, so I changed that, too.

<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" ) && (theForm.cardno.value == "" || 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) {

validLength = true;

if (type == "Visa") {

if (ccnum.length != 19){validLength = false} // I ued 19, 16 digits plus 3 dashes

// Visa: length 16, prefix 4, dashes optional.

var re = /^4d{3}-?d{4}-?d{4}-?d{4}$/;

} if (type == "MC") {

if (ccnum.length != 19){validLength = false}

// Mastercard: length 16, prefix 51-55, dashes optional.

var re = /^5[1-5]d{2}-?d{4}-?d{4}-?d{4}$/;

} if (type == "Disc") {

if (ccnum.length != 19){validLength = false}

// Discover: length 16, prefix 6011, dashes optional.

var re = /^6011-?d{4}-?d{4}-?d{4}$/;

} if (type == "AmEx") {

if (ccnum.length != 18){validLength = false}

// American Express: length 15, prefix 34 or 37.

var re = /^3[4,7]d{13}$/;

} if (type == "Diners") {

if (ccnum.length != 17){validLength = false}

// Diners: length 14, prefix 30, 36, or 38.

var re = /^3[0,6,8]d{12}$/;

}

if (!validLength) return false;

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>
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — I had to edit the above post, because I repeated my original error.

it's supposed to be:

if (ccnum.length !=19){validLength = false}

not:

if (ccnum != 19){validLength = false}
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — I suppose also that if you wanted an alert you could add this line, as well, immediately above the existing line, as shown.

if(!validLength){alert("You entered an incorrect number of digits")}

if (!validLength) return false;
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — Warren,

I must commend you for your patience.

I certainly *do* appreciate the assistance I have been getting from you.

Right now, there are some minor bugs I am trying to work out on function isValidCreditCard.

function validate was missing some = like:

if ((theForm.paymentm = "Visa".

Of course those are minor but they take time to pickout.

I am sure I am having similar issues with function isValidCreditCard

As soon as I resolve that, I will come back to report what is going on.

Thanks again for all the help.
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — Ok, I have gotten all the bugs worked out but still it is still submitting.

The alert, for some strange reason, is not being recognized by the code.

However, I think I found out why the validation isn't working,

I did an additional validation on the processing page called process.asp.

On that page, I am passing the form variable called cardno to from this current page we have been working on to the processing page and I am basically saying that if the card number is equal to or less than 14, ask the user to enter correct number.

This extra validation is done using ASP and I have been trying to modify it so it checks for each payment type before going forward with the processing with the below code:
<i>
</i>If (Request.Form("paymentm") = 'MC' OR Request.Form("paymentm") = 'Disc' OR Request.Form("paymentm") = 'Visa') AND (Request.Form("cardno") = "" OR len(Request.Form("cardno")) &lt; 16 ) Then
Response.Redirect "checkout.asp?msg=" &amp; Server.URLEncode ("Mastercard or Visa or Discover cards must be 16 digits.")
Elseif (Request.Form("paymentm") = 'AmEx') AND (Request.Form("cardno") = "" OR len(Request.Form("cardno")) &lt; 15 ) Then
Response.Redirect "checkout.asp?msg=" &amp; Server.URLEncode ("American Express card must be 15 digits.")
Elseif (Request.Form("paymentm") = 'Diners') AND (Request.Form("cardno") = "" OR len(Request.Form("cardno")) &lt; 14 ) Then
Response.Redirect "checkout.asp?msg=" &amp; Server.URLEncode ("Diners club card must be 14 digits.")

Elseif Request.Form("cardname") = "" OR len(Request.Form("cardname")) &lt;=6 Then
Response.Redirect "checkout.asp?msg=" &amp; Server.URLEncode ("Please fill in a correct credit card name.")


This is not working so far.

Do you know anything about ASP?
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — No. Sorry. But, I did notice that you are calling the function from an onchange event in a select list, but the function itself is set up as a "return" function. The return isnt' being checked.

Maybe you should just eliminate the returns and instead put alert code.

if (!re.test(ccnum)){alert("You entered an invalid number"}

No point in returning true or false, because it isn't being checked.

Am I making sense?

There is one other place in that function as well that returns true or false. I'd change that as well.

If the alert I initially inserted isn't working, then I'd check to see just what ccnum is.

In the first line of the function, put:

alert(ccnum)

See, what the heck you are dealing with to start.
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — You know, you aren't even passing the card number to that function.

Try the the select list like this:

<select name="paymentm" onChange="isValidCreditCard(this.value,theForm.cardno.value)">

<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>

Of course, you'll have to make sure that the user has entered a credit card number BEFORE selecting the credit card type. Otherwise, set up a button to call the function and not use the onchange event.
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — as soon as I put the alert, I started getting "undefined" when I select a credit card.

So should I change the function to to onSubmit="return isValidCreditCard(this)" ?
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — I wouldn't use it as a "return" function. I'd get rid of the returns in the function and replace it with an alert.

No wonder it was undefined. Nothing was being passed to that function.
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — When I remove the returns, I get "undefined is null or not an object"
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — ..
Copy linkTweet thisAlerts:
@Warren86Dec 04.2004 — And this way, with a button:

<select name="paymentm">

<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>

<input type=button value="Validate" onclick="isValidCreditCard(paymentm.value,theForm.cardno.value)">

I'll bet there's not even a form named theForm.
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — You have been absolutely great.

Thanks for all the help.

At this point, I believe that I *must* the ASP validation rule.

Everything we have tried so far has failed to work.

Let me resolve the bug with the server side code and I will be back to advise.
Copy linkTweet thisAlerts:
@janiceauthorDec 04.2004 — ok,

I got it working now.

Your code, coupled with server side validation did the trick.

Thanks for all the help.
×

Success!

Help @janice spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...