Credit Card Validation Function

Dzhuneyt Ahmed - Author of this post

By: Dzhuneyt Ahmed

Posted · 1 min read

Outdated: This post performs basic regex validation of credit card numbers. If you handle real card data, you must comply with PCI-DSS standards. In practice, delegate card handling entirely to a payment processor like Stripe or Braintree — never store or process raw card numbers yourself.

Credit Card Validation Function

Whethere you are building a shopping cart or just requesting your customer’s credit card number for some purpose, we are constantly faced with abusers that fill invalid or fake credit card numbers. This little function courtesy of SoftwareProjects.com will help you avoid that.

function validCC($cc_num) { $pattern = "/^3[47]d{13}$/";//American Express if (preg_match($pattern,$cc_num)) { return true; }

$pattern = "/^([30|36|38]{2})([0-9]{12})$/";//Diner's Club if (preg_match($pattern,$cc_num)) { return true; }

$pattern = "/^6011d{12}$/";//Discover Card if (preg_match($pattern,$cc_num)) { return true; }

$pattern = "/^5[12345]d{14}$/";//Mastercard if (preg_match($pattern,$cc_num)) { return true; }

$pattern = "/^4d{12}(ddd){0,1}$/";//Visa if (preg_match($pattern,$cc_num)) { return true; }

$pattern = "/^30[012345]d{11}$/";//Diners if (preg_match($pattern,$cc_num)) { return true; }

$pattern = "/^3[68]d{12}$/";//Diners #2 if (preg_match($pattern,$cc_num)) { return true; }

// Not valid return false;
}

Usage is as follows:

echo validCC("card_number_here");

Of course, it can’t check if the credit card really exists and if it has any ballance, because that’s confidential information, but at least you won’t get random numbers anymore.

Dzhuneyt Ahmed

Dzhuneyt

Helping teams build reliable cloud infrastructure — without the bloated bill.

Social

My Other Blogs

© 2026 Dzhuneyt Ahmed. All rights reserved.