How to validate MasterCard number using Regular Expression?


Mastercard is a multinational financial services company that has provided payment processing services to clients globally since its establishment in 1966. Its headquarters remain based in New York, USA. It marked as one of the biggest payment systems in the world, with rivals Visa and American Express. They stand out and are well fitted for both of the consumer and business need due to the large range of goods they provide, which may involve credit cards, debit cards, and prepaid cards.

Among them are prepaid cards, debit cards, and credit cards. To distribute these card options globally, it works with financial institutions worldwide so that they can issue Mastercard-branded cards to businesses and individuals’ people. This strategic partnership ensures that the reach of their quality services is extensive throughout the world.

Methods

Here are three different methods to validate Mastercard numbers using Regular Expression −

Method 1: Using Lookahead Assertions

Method 2: Using Backreferences

Method 1: Using Lookahead Assertions

Lookahead assertions can be used to verify the Mastercard number's checksum. The Luhn procedure is used to calculate the checksum, which entails doubling every other digit by 2, then adding those results to the non-multiplied digits. The total amount should be 10 times divisible.

Syntax

Regular expressions only utilise lookahead assertions to match a pattern if it is or is not followed by another pattern. The following syntax can be used to validate a MasterCard number using regular expressions and lookahead assertions −

^(5[1-5][0-9]{2}(?=[\s|-])|\d{4}(?=[\s|-])?\d{4}(?=[\s|-])?\d{4}(?=[\s|-])?\d{1,4}(?!\d))$

Let's break down the syntax to understand how it works −

  • matches the beginning of the string.

    5[1-5][0-9]{2}(?=[\s|-])

    matches a MasterCard number that begins with 5, is followed by a digit between 1 and 5, two more digits, and a space or hyphen. A positive lookahead assertion (?=[s|-]) is used for this, which determines if the following character is a hyphen or whitespace without adding it in the match.

    |\d{4}(?=[\s|-])?\d{4}(?=[\s|-])?\d{4}(?=[\s|-])?\d{1,4}(?!\d)

    matches a MasterCard number which does not start with 5, is not followed by another digit, has a total of 16 digits (with optional blank characters or hyphens between every four digits), and is not followed by a 5. This is obtained by using a negative lookahead assertion (?!d), which assesses whether the next character is a digit or not.

  • $

    matches the end of the string.

Algorithm

An approach for validating MasterCard numbers with lookahead assertions and a regular expression −

Step 1 − Make a regular expression pattern that matches MasterCard numbers by first defining it. The string anchor's beginning () and ending ($) should represent the starting and ending points of the pattern, respectively.

Step 2 − Check that the number satisfies the following requirements using lookahead assertions−

  • 5 must be the first digit of the number. To verify this, use the lookahead assertion (? =5).

  • The second digit ought to fall between 1 and 5. To verify for this, use the lookahead assertion (? = [1-5]).

  • The number needs to have 16 digits. To check for this, use the lookahead assertion (? =d16).

Step 3 − To accommodate the two different MasterCard number formats—four sets of four digits separated by spaces or dashes, or 16 digits without spaces or dashes—use the alternation operator (|). For instance, (? :(?:d4[s-]?){3}\d{4}|(?:\d{16}))

Step 4 − To validate MasterCard numbers in your code, utilise the regular expression pattern. The number is a legitimate MasterCard number if the pattern matches the given string.

Overall, this technique checks a MasterCard number against a list of requirements using lookahead assertions, and then matches the number against a regular expression pattern in one of two formats.

Example 1

In this example, we define the function isMastercard, which accepts a string cardNumber as input and checks the validity of the number using a Regular Expression to determine if it is a legitimate Mastercard number. The Regular Expression pattern is divided into two sections −

  • The first portion, ([1-5][0-9]]2), corresponds to the first six digits of a Mastercard number, which must begin with a "5", be followed by a digit between "1" and "5", and then two more digits between "0" and "9". A lookahead assertion is not made in this section of the pattern.

  • The second component, (?=d12$)[0-9]8$, is a Lookahead Assertion that verifies that the card number's remaining digits are made up of exactly 12 digits, followed by 8 more digits. Only utilised for lookahead, this portion of the pattern is excluded from the actual match.

The aforementioned pattern is defined as a Regular Expression object pattern in the isMastercard method, and the cardNumber string is checked to see if it matches the pattern using the regex_match function. The input is a legitimate Mastercard number if it does, in which case we return true. We return false if not.

We define a sample Mastercard number as a string in the main function and feed it to the isMastercard function. The validity of the card number is then printed out.

Remember that there are other Regular Expression patterns that can be used to validate Mastercard numbers; this is just one example. Different systems and applications may employ various patterns.

#include <iostream>
#include <regex>
using namespace std;

bool isMastercard(string cardNumber) {
   regex pattern("^(5[1-5][0-9]{2})(?=\d{12}$)[0-9]{8}$");
   return regex_match(cardNumber, pattern);
}

int main() {
   string cardNumber = "5432345678901234";
   bool isValid = isMastercard(cardNumber);
   if (isValid) {
      cout << "Mastercard number " << cardNumber << " is valid" << endl;
   } else {
      cout << "Mastercard number " << cardNumber << " is invalid" << endl;
   }
   return 0;
}

Output

Mastercard number 5432345678901234 is invalid

Method 2. Using Backreferences

The Mastercard number's Luhn checksum can be verified using backreferences. We can employ the following algorithm to verify the Luhn checksum −

  • Double each subsequent digit, beginning with the rightmost one (apart from the final two).

  • Add up all the resulting digits, including the non-doubled digits

  • The resulting sum must be divisible by 9 if the doubled digit is more than 9.

Syntax

The following syntax can be used to validate a MasterCard number using regular expressions and backreferences −

^5[1-5] [0-9]{2}(\s|-)?[0-9]{4}(\s|-)?[0-9]{4}(\s|-)?[0-9]{4}$

This regular expression uses the optional backreference (s|-)? to match a space or hyphen.

As a result, the user has several formats to enter the card number, like "5555 5555 5555 4444" and "5555-5555-5555-4444".

The first character and last characters of the string, as and $, are both matches for the regular expression. The MasterCard number's first three digits, which are represented by [1-5][0-9]2, must be between 51 and 55. Three times [0-9]4 are repeated to represent the remaining digits, with the optional s|- backreference placed in between each repetition.

Algorithm

Here is a step-by-step algorithm of using backreferences to validate MasterCard numbers using regular expressions −

Step 1 − Define the regular expression−

^5[1-5][0-9]{14}$

Any string that has the number 5, a number between 1 and 5, and 14 digits between 0 and 9 is matched by this regular expression. The entire string is guaranteed to follow this pattern thanks to the and $ anchors.

Step 2 − Add a backreference to check the last digit−

^5[1-5][0-9]{14}([0-9])$

The parentheses around the [0-9] create backreference that captures last digit of the string.

Step 3 − Add the Luhn algorithm check−

^5[1-5][0-9]{14}([0-9])([0-9]{2})?$

The regular expression's ([0-9]2]?) at the end allows for the optional appendage of a two-digit number to the string's conclusion. To carry out the Luhn algorithm check, this is necessary.

Step 4 − Use a backreference to reverse the string −

^5[1-5][0-9]{14}([0-9])([0-9]{2})?$ -> ^([0-9])([0-9]{2})?[0-9]{14}5[1-5]$

The backreferences method is used in this step to reverse the string's order. The last couple of digits of the string are caught by the ([0-9]) ([0-9]2])? what's more, are kept in backreferences 1 and 2, separately. These backreferences can then be used to reverse the string.

Step 5 − Apply the Luhn algorithm to the reversed string −

^([0-9])([0-9]{2})?[0-9]{14}5[1-5]$ -> ^([0-9])([0-9]{2})?[0-9]{14}(?:([0-9])(?:(?:(\d)(?=\d{0,13}$))?\d)?([02468])(?=\d{0,11}$))?$

The Luhn algorithm check is now added to the reversed string. The (? :([0-9])(? :(?='d'0,13'$))? ([02468])(?='d'0,11'$))? The Luhn algorithm is used to check the regular expression at its conclusion. It confirms that the entire amount is divisible by 10 by checking the sum of the digits in the odd positions (beginning from the right) and the sum of the digits in the even positions (doubled if necessary and then summed).

Step 6 − Validate the input−

Using a function like preg_match in PHP or re.match in Python, the input can be checked against the regular expression. The input is a legitimate MasterCard number if it matches the regular expression.

Example 2

In this example, we construct a validate MasterCard function that accepts a string representing a Mastercard number as input and returns true if the text is real and false otherwise. We apply a regular expression to match a valid Mastercard number's structure.

The regular expression pattern 5[1-5] is employed. [0-9]14$. The string pattern in question highlights a sequence of 15 integers, which strictly starts or ends with the digit '5', followed by any single digit between one to five, and finally, concluding with fourteen digits (0-9) of any choice. Essentially, the starting mark represents the beginning while the symbol '$' serves as an endpoint.

To find out whether the input card Number resembles the regular expression pattern, we use the regex match function. We return true if it does resemble, or we return false if it does not resemble.

We define a sample Mastercard number in the main function and pass it to the validate MasterCard function. We print a message showing whether the number is valid or invalid. If the number is valid, we print a message indicating that.

#include <iostream>
#include <regex>
using namespace std;

bool validateMastercard(string cardNumber) {
   regex pattern("^5[1-5][0-9]{14}$");
   return regex_match(cardNumber, pattern);
}

int main() {
   string cardNumber = "5555555555554444";
   if (validateMastercard(cardNumber)) {
      cout << "Valid Mastercard number" << endl;
   } else {
      cout << "Invalid Mastercard number" << endl;
   }
   return 0;
}

Output

Valid Mastercard number

Conclusion

In conclusion, validating a Mastercard number using regular expressions can be a very useful tool in ensuring that the inputted card number is valid and meets the specific format requirements. Regular expressions allow for a specific pattern to be defined for a Mastercard number, which can then be used to quickly and easily validate any inputted numbers.

Updated on: 31-Jul-2023

206 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements