DebugPointer
Published on

Regex for Visa Card validation

Regex for Visa Card validation

Visa facilitates electronic funds transfers throughout the world, most commonly through Visa-branded credit cards, debit cards and prepaid cards. They don't issue cards, but, they provide financial institutions ability to launch Visa branded cards. In this article let's understand how we can create a regex for VISA card and how regex can be matched for VISA card.

Regex (short for regular expression) is a powerful tool used for searching and manipulating text. It is composed of a sequence of characters that define a search pattern. Regex can be used to find patterns in large amounts of text, validate user input, and manipulate strings. It is widely used in programming languages, text editors, and command line tools.

Structure of Visa Card

  • It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.
  • It should not contain any alphabet or special characters.
  • It should start with 4.
  • If the cards have 13 digits the next 12 digits should be any number between 0-9.
  • If the cards have 16 digits the next 15 digits should be any number between 0-9.

Regex for checking if Visa Card is valid or not

Regular Expression-

/^4[0-9]{12}(?:[0-9]{3})?$/gm

Test string examples for the above regex-

Input StringMatch Output
2233172283924does not match
4312312312312matches
4333121212does not match
4912001201020matches

Here is a detailed explanation of the above regex-

/^4[0-9]{12}(?:[0-9]{3})?$/gm

^ asserts position at start of a line
4 matches the character 4 with index 5210 (3416 or 648) literally (case sensitive)
Match a single character present in the list below [0-9]
{12} matches the previous token exactly 12 times
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
Non-capturing group (?:[0-9]{3})?
? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
Match a single character present in the list below [0-9]
{3} matches the previous token exactly 3 times
0-9 matches a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)
$ asserts position at the end of a line
Global pattern flags
g modifier: global. All matches (don't return after first match)
m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)
x modifier: extended. Spaces and text after a # in the pattern are ignored

Hope this article was useful to match VISA card number regex pattern.