PHP Validate Credit Card format

///PHP Validate Credit Card format

PHP Validate Credit Card format

Are you in a bind trying to figure out if that user input credit card number is valid as far as format goes. Not just length but the actual combination of numbers as well? Well then here is a quickie solution. Due to the sensitive nature of the topic though I will omit the example portion of this code but the concept of use in this particular version is take a select box of the various types then a standard input text and plug the numbers in. It takes the card choice and numbers and compares the 2 for a valid match. Note: I can’t guarantee 100% that this will work with every credit card out there. But I have yet to run into an issue with it to date. \r\n\r\n
\r\nfunction validateCC($cc_num, $type)\r\n{\r\n    if($type == "American")\r\n    {\r\n        $pattern = "/^([34|37]{2})([0-9]{13})$/";\r\n        if(preg_match($pattern,$cc_num)){$verified = true;\r\n        }\r\n        else\r\n        {\r\n        $verified = false;\r\n        }\r\n    }\r\n    elseif($type == "Dinners")\r\n    {\r\n        $pattern = "/^([30|36|38]{2})([0-9]{12})$/";\r\n        if(preg_match($pattern,$cc_num))\r\n        {\r\n        $verified = true;\r\n        }\r\n        else\r\n        {\r\n        $verified = false;\r\n        }\r\n    }\r\n    elseif($type == "Discover")\r\n    {\r\n        $pattern = "/^([6011]{4})([0-9]{12})$/";\r\n        if(preg_match($pattern,$cc_num))\r\n        {\r\n        $verified = true;\r\n        }\r\n        else\r\n        {\r\n        $verified = false;\r\n        }\r\n    }\r\n    elseif($type == "Master")\r\n    {\r\n        $pattern = "/^([51|52|53|54|55]{2})([0-9]{14})$/";\r\n        if(preg_match($pattern,$cc_num))\r\n        {\r\n        $verified = true;\r\n        }\r\n        else\r\n        {\r\n        $verified = false;\r\n        }\r\n    }\r\n    elseif($type == "Visa")\r\n        {\r\n        $pattern = "/^([4]{1})([0-9]{12,15})$/";\r\n        if(preg_match($pattern,$cc_num))\r\n        {\r\n           $verified = true;\r\n        }\r\n        else\r\n        {\r\n           $verified = false;\r\n        }\r\n    }\r\n    else\r\n    {\r\n	    verified = false;\r\n    }\r\n    if($verified == false)\r\n    {\r\n	    return "invalid";\r\n    }\r\n    else\r\n    {\r\n	    return "valid";\r\n    }\r\n}\r\n
By | 2014-01-05T10:23:51+00:00 March 8th, 2012|Code, PHP|0 Comments

About the Author:

Not much to know about me, I'm a 35+ year old coder, geek, gamer..

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: