Visa credit card number validation

Q

All credit card numbers issued by Visa must start with a 4 and have 13 or 16 digits. For example, 346997719493686 is a valid Visa credit card number.

How to write a single regular expression to validate a Visa credit card number described above?

✍: FYIcenter.com

A

Here is the regular expression for Visa credit card number validation:

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

^ - begin of the string
4 - matches 4
[0-9] - any decimal digit
{12} - repeating 12 times
(?:[0-9]{3}) - non-capturing group of 3 digits
? - match previous group 1 time or nothing
$ - end of the string

Click the button to test this regular expression here online:

2013-01-22, 0👍, 0💬