Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 9 of 9
  1. #1
    New Coder
    Join Date
    Nov 2008
    Posts
    27
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Credit Card Matching Regexp

    Here's another problem I'm having, I have to validate credit card types. My code worked originally. I simply checked the prefix for each type then verified the length with an if statement. However, I decided to change the code so that only numbers would work after the prefix (as the old code would have allowed any character).

    This is the code I have:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Credit Card Validation</title>
    <link rel="stylesheet" type="text/css" href="default.css" />
    <script type="text/javascript">
    
    function checkCC(myForm)
    {
    	var ccType;
    	var ccLength;
    	var ccNum = myForm.cardNum.value; 
    	if (myForm.cardType.selectedIndex == 0)
    	{
    		ccType = "Visa";
    	}
    	
    	else if (myForm.cardType.selectedIndex == 1)
    	{
    		ccType = "MasterCard"
    	}
    	
    	else if (myForm.cardType.selectedIndex == 2)
    	{
    		ccType = "AmericanExpress"
    	}
    	
    	 switch(ccType)
        {
    		case "Visa":
    		{
            	valid = /^4\d{12}(?:\d{3})?$/;
    			
    			if (valid.test(myForm.cardNum.value))
    			{
    				alert("This is a Valid Visa Card");
    				return true;
    			}
    			
    			else
    			{
    				alert("This Card Number is Invalid For Visa");
    				return false;
    			}
            	break;
    		}
    		
          	case "MasterCard":
    		{
            	  	valid = /^5[1-5]\d{14}$/;
    			
    			if (valid.test(myForm.cardNum.value))
    			{
    				alert("This is a Valid MasterCard Card");
    			}
    			
    			else
    			{
    				alert("This Card Number is Invalid For MasterCard");
    			}
            	break;
    		}
    
          	case "AmericanExpress":
    		{
            	valid = /^3[47]\d{13}$/;
    			
    			if (valid.test(myForm.cardNum.value))
    			{
    				alert("This is a Valid American Express Card");
    				//return true;
    			}
    			
    			else
    			{
    				alert("This Card Number is Invalid For American Express");
    				//return false;
    			}
            	break;
    		}
    
          	default:
            	myForm.cardNum.value = null;
            	alert("Card type not found");
    			return false;
        }
    }
    </script>
    </head>
    
    <body>
    
    <h1>Credit Card Validator</h1>
    <table>
    <form name="creditCard">
    
    <tr>
    	<td><span class="labels">Card Type:</span></td>
    
    	<td>
    		<select name="cardType" size="3">
    			<option name="visa">Visa</option>
        		<option name="mc">Master Card</option>
        		<option name="amex">American Express</option>
    		</select>
       	</td>
        
    <tr>
    	<td><span class="labels">Card Number:</span></td>
    	<td><input name="cardNUm" type="text" size=30 value="" /></td>
    </tr>
    
    <tr><td colspan="2">&nbsp;</td></tr>
    
    <tr>
    	<td>
    	<input type="button" value="Death to All" 
    	 style="background-color:#666666 !important"
    	 onclick="return(checkCC(this.form,))" />
        </td>
    </tr>
    </form>
    </table>
    
    </body>
    </html>
    Upon pressing the button nothing happens, I'm completely unsure where I went wrong as all the code seems valid... Please help. Thanks in advance.

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,688
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    Did you test it with FireBug? No errors???
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #3
    Regular Coder
    Join Date
    Jun 2008
    Posts
    102
    Thanks
    6
    Thanked 9 Times in 9 Posts
    You speeled s0me th!ngz wrawng.

    Here you go...

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Credit Card Validation</title>
    <link rel="stylesheet" type="text/css" href="default.css" />
    <script type="text/javascript">
    
    function checkCC(myForm)
    {
    	var ccType;
    	var ccLength;
    	var ccNum = myForm.cardNum.value; 
    	if (myForm.cardType.selectedIndex == 0)
    	{
    		ccType = "Visa";
    	}
    	
    	else if (myForm.cardType.selectedIndex == 1)
    	{
    		ccType = "MasterCard"
    	}
    	
    	else if (myForm.cardType.selectedIndex == 2)
    	{
    		ccType = "AmericanExpress"
    	}
    	
    	 switch(ccType)
        {
    		case "Visa":
    		{
            	valid = /^4\d{12}(?:\d{3})?$/;
    			
    			if (valid.test(myForm.cardNum.value))
    			{
    				alert("This is a Valid Visa Card");
    				return true;
    			}
    			
    			else
    			{
    				alert("This Card Number is Invalid For Visa");
    				return false;
    			}
            	break;
    		}
    		
          	case "MasterCard":
    		{
            	  	valid = /^5[1-5]\d{14}$/;
    			
    			if (valid.test(myForm.cardNum.value))
    			{
    				alert("This is a Valid MasterCard Card");
    			}
    			
    			else
    			{
    				alert("This Card Number is Invalid For MasterCard");
    			}
            	break;
    		}
    
          	case "AmericanExpress":
    		{
            	valid = /^3[47]\d{13}$/;
    			
    			if (valid.test(myForm.cardNum.value))
    			{
    				alert("This is a Valid American Express Card");
    				//return true;
    			}
    			
    			else
    			{
    				alert("This Card Number is Invalid For American Express");
    				//return false;
    			}
            	break;
    		}
    
          	default:
            	myForm.cardNum.value = null;
            	alert("Card type not found");
    			return false;
        }
    }
    </script>
    </head>
    
    <body>
    
    <h1>Credit Card Validator</h1>
    <table>
    <form name="creditCard">
    
    <tr>
    	<td><span class="labels">Card Type:</span></td>
    
    	<td>
    		<select name="cardType" size="3">
    			<option name="visa">Visa</option>
        		<option name="mc">Master Card</option>
        		<option name="amex">American Express</option>
    		</select>
       	</td>
        
    <tr>
    	<td><span class="labels">Card Number:</span></td>
    	<td><input name="cardNum" type="text" size=30 value="" /></td>
    </tr>
    
    <tr><td colspan="2">&nbsp;</td></tr>
    
    <tr>
    	<td>
    	<input type="button" value="Death to All" 
    	 style="background-color:#666666 !important"
    	 onclick="return(checkCC(this.form))" />
        </td>
    </tr>
    </form>
    </table>
    
    </body>
    </html>

  • Users who have thanked hotwheelharry for this post:

    ParadoxKing (12-06-2010)

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    27,688
    Thanks
    80
    Thanked 4,655 Times in 4,617 Posts
    Quote Originally Posted by hotwheelharry View Post
    You speeled s0me th!ngz wrawng.
    LOL! NICE!!!!

    Also, those so-called tests are *NOT* checking for valid CC numbers. They aren't doing the minimal check-digit test, so all you really know is if the card number is in the valid *range* for the given type.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #5
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts
    I worked in a bank for 5 years, and one thing I can tell you from that is: Never rely on verifyable card details, nor the 1 digit prefix. Some vendors can have different length card numbers, and some cards can be "hybrid" mastercard and visa (for example) with a different prefix.

    Though things are becoming more standardised, you should give a pretty wide berth to allowable digit counts, and only take the first digit as a guide, not an absolute.
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog

  • #6
    Super Moderator
    Join Date
    Feb 2009
    Location
    England
    Posts
    539
    Thanks
    8
    Thanked 63 Times in 54 Posts
    I went off to read, out of personal interest. If you want to validate card details, do this:

    http://en.wikipedia.org/wiki/Luhn_algorithm
    lamped.co.uk :: Design, Development & Hosting
    marcgray.co.uk :: Technical blog

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,316
    Thanks
    203
    Thanked 2,566 Times in 2,544 Posts
    Code:
    <form name = "myForm">
    <p> Enter credit card number <input type = "text" name = "CCNumber" maxlength = "16" onblur = "luhnCheck(this)"></p>
    </form>
    
    <script type = "text/javascript">
    
    function luhnCheck(cardNum)  {
    
    var failflag = 0;
    cardNum = cardNum.value;
    cardNum = cardNum.replace(/[^\d]/g, "");  // strip non-digits
    if (cardNum.length <15 || cardNum.length > 16) {failflag = 1}
    var firstDigit = cardNum.substr(0,1);
    if (firstDigit < 3 || firstDigit > 6) {failflag = 1}
    
    if (firstDigit == 3) {
    if (!/^3[47][0-9]{13}$/.test(cardNum)) {
    alert ("American Express numbers must be 15 digits starting with 34 or 37");  // test example 378282246310005
    }
    }
    if (firstDigit == 4) {
    if (!/^4[0-9]{12}(?:[0-9]{3})?$/.test(cardNum)) {
    alert ("Visa numbers must be 16 digits starting with 4");  // test example 4111111111111111
    }
    }
    if (firstDigit == 5) {
    if (!/^5[1-5][0-9]{14}$/.test(cardNum)) {
    alert ("MasterCard numbers must be 16 digits starting with 51 - 55");  // test example 5105105105105100
    }
    }
    
    var ccArray = cardNum.split("");
    ccArray = ccArray.reverse();
    
    var digitString = "";
    var digitSum = 0;
    for (var counter = 0; counter < ccArray.length; counter++ )	{
    var current_digit = parseInt( ccArray[counter] );
    if (counter %2 != 0) {
    ccArray	[counter] *= 2;
    }
    digitString += ccArray[counter];
    }
    
    for (counter = 0; counter < digitString.length; counter ++) {
    current_digit = parseInt(digitString.charAt(counter));
    digitSum += current_digit
    }
    if (digitSum % 10 != 0 ) {failflag = 1}
    
    if (failflag == 0) {
    alert ("The card number is valid \(passes Luhn algorithm\)  ")
    return true
    }
    else {
    alert ("The card number is INVALID - please re-enter it ");
    document.myForm.CCNumber.value = "";
    document.myForm.CCNumber.focus();
    return false
    }
    
    }
    
    </script>
    You can easily check the card brand using firstDigit to determine.


    Quizmaster: What season is said to start on the longest day in December?
    Contestant: Spring.
    Quizmaster: December, for God's sake!
    Contestant: Summer.
    Last edited by Philip M; 12-05-2010 at 10:38 AM.

  • #8
    Regular Coder
    Join Date
    Nov 2009
    Posts
    247
    Thanks
    4
    Thanked 22 Times in 22 Posts
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Any Title</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script type="text/javascript">
    
    	function validate(nForm){
       	
    		var ccnum = nForm['credit_card_number'].value.replace(/ |-/g,"");
    		var nTypes = document.getElementsByName('creditcard');
    		var isType = "";
    		for (i=0; i<nTypes.length; i++)
    			{
    			 if (nTypes[i].checked)
    				{
    				 isType = nTypes[i].value;
    				}
    			}
    		if (isType.length == "")
    			{
    			 alert("Please enter a credit card number");
    			 return false;			
    			}
    		if (isType == "Visa")
    			{
    			 isRegEx = /^4\d{3}\d{4}\d{4}\d{4}$/
    			}
    		if (isType == "MasterCard")
    			{
    			 isRegEx = /^5[1-5]\d{2}\d{4}\d{4}\d{4}$/
    			} 
    		if (isType == "Discover")
    			{
    			 isRegEx = /^6011\d{4}\d{4}\d{4}$/
    			} 
    		if (isType == "AMEX")
    			{
    			 isRegEx = /^3[4,7]\d{13}$/
    			} 		
    		var isDigit = "";
    		if (isRegEx.test(ccnum))
    			{			 
      			 checksum = 0;
       			 for (i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2)
    				{checksum += parseInt(ccnum.charAt(i-1))}
      			 for (i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2)
    				{
    		 	 	 isDigit = parseInt(ccnum.charAt(i-1)) * 2;
          		  		 if (isDigit < 10){checksum += isDigit}
    				      else {checksum += (isDigit-9)}
       				}
      	 		if ((checksum % 10) != 0)
    				{
    				 alert("Invalid credit card number");
    				 nForm['credit_card_number'].value = "";
    				 nForm['credit_card_number'].focus();
    				 return false;
    				}
    			}
    		else 	{
    			 alert("Incorrect credit card number format");
    			 nForm['credit_card_number'].value = "";
    			 nForm['credit_card_number'].focus();
    			 return false;
    		 	}		
    		if (nForm['Customer'].value == "" || nForm['Address1'].value == "" ||
    			 nForm['City'].value == "" || nForm['state'].value == "" || 
    			 nForm['Zip'].value == "" || nForm['birth_date'].value == "")
    			{
    			 alert("Complete all required fields");
    			 return false;
    			}
    		return true;
    	}
    
    	function init(isBtn){
    		
    		document.forms[0]['credit_card_number'].value = "";
    		document.forms[0]['expiration_month'].selectedIndex = 0;
    		document.forms[0]['expiration_year'].value = "";		
    	}
    	
    	 var usStates = [];
    	 usStates['stateList'] = ['Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 
    				  'Colorado', 'Connecticut', 'Delaware', 'Florida', 'Georgia',
    				  'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 
    				  'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 
    				  'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 
    				  'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico',
    				  'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 
    				  'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota',
    				  'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington',
    				  'West Virginia', 'Wisconsin', 'Wyoming']; 
    
    	function initStates(){
    
    		var nForm = document.forms[0];
    		var nList = nForm['state'];
    		nList.length = 1;
    		var allStates = usStates['stateList'];
    		for (each in allStates)
    			{
    			 var nOption = document.createElement('option'); 
    			 var nData = document.createTextNode(allStates[each]); 
    			 nOption.value = allStates[each]; 
    			 nOption.appendChild(nData); 
    			 nList.appendChild(nOption); 
    			}
    		nForm.onsubmit = function()
    			{
    			 return validate(this);
    			}
    	}
    
    	navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', initStates, false) : addEventListener('load', initStates, false);	
    
    </script>
    </head>
       <body>
    	<p>Please enter information in all required fields '*'.
    	Then click <i>Submit</i> to send your order. To clear the form, click <i>Reset</i>.
    	Thank you for cooperation!</p>
    	<!-- Form begins -->
             <form name="Feedback_form" method="post" action="">
    	       <table width="100%" border="0">
                        <tr>
                             <td width="140">
                                  Name*
                             </td>
                             <td>
                                  <input name="Customer" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Address1*
                             </td>
                             <td>
                                  <input name="Address1" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Address2
                             </td>
                             <td>
                                  <input name="Address2" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  City*
                             </td>
                             <td>
                                  <input name="City" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  State*
                             </td>
                             <td>
                                  <select name="state">
    			      	<option value="">
    				     Choose your state
    				</option>
    			      </select>
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Zip*
                             </td>
                             <td>
                                  <input name="Zip" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Telephone
                             </td>
                             <td>
                                  <input name="Telephone" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Date of Birth*
                             </td>
                             <td>
                                  <input name="birth_date" size="30">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Select Credit Card*
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Visa
                             </td>
                             <td>
                                  <input type="radio" name="creditcard" value="Visa" onclick="init(this)">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  MasterCard
                             </td>
                             <td>
                                  <input type="radio" name="creditcard" value="MasterCard" onclick="init(this)">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  AMEX
                             </td>
                             <td>
                                  <input type="radio" name="creditcard" value="AMEX" onclick="init(this)">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Discover
                             </td>
                             <td>
                                  <input type="radio" name="creditcard" value="Discover" onclick="init(this)">
                             </td>
                        </tr>
                        <tr>
                             <td width="140">
                                  Credit Card Number*
                             </td>
                             <td>
                                  <input name="credit_card_number" size="30">
                             </td>
    
                        </tr>
                        <tr>
                             <td width="140">
                                  Expiration Month*
                             </td>
                             <td>
                                  <select name="expiration_month">
                                       <option value="1">
                                            1
                                       </option>
                                       <option value="2">
                                            2
                                       </option>
                                       <option value="3">
                                            3
                                       </option>
                                       <option value="4">
                                            4
                                       </option>
                                       <option value="5">
                                            5
                                       </option>
                                       <option value="6">
                                            6
                                       </option>
                                       <option value="7">
                                            7
                                       </option>
                                       <option value="8">
                                            8
                                       </option>
                                       <option value="9">
                                            9
                                       </option>
                                       <option value="10">
                                            10
                                       </option>
                                       <option value="11">
                                            11
                                       </option>
                                       <option value="12">
                                            12
                                       </option>
                                  </select>
                             </td>
                        </tr>
                        <tr>
                             <td width="140" valign="top">
                                  Expiration Year*
                             </td>
                             <td>
                                 <select name="expiration_year">
    				<option value="2007">
    					2007
    				</option>
    				<option value="2008">
    					2008
    				</option>
    				<option value="2009">
    					2009
    				</option>
    				<option value="2010">
    					2010
    				</option>
    				<option value="2011">
    					2011
    				</option>
    				<option value="2012">
    					2012
    				</option>
    				<option value="2013">
    					2013
    				</option>
    			     </select>
                             </td>
                        </tr>
                        <tr>
                             <td></td>
                             <td>
                                  <input type="submit" name="Submit" value="Submit Order">&nbsp;<input type="reset" name="Reset" value="Reset">
                             </td>
                        </tr>
                   </table>
              </form>
    	<!-- Form ends -->
         </body>
    
    </html>

  • #9
    New Coder
    Join Date
    Nov 2008
    Posts
    27
    Thanks
    4
    Thanked 0 Times in 0 Posts
    hotwheelharry, gave me what I needed. Thanks.


  •  

    Tags for this Thread

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •