Code snippets 4U - RegEx to validate creditcards / email

Hi all, gonna start giving back a bit…

Using Regular expression to check if a string is a

Valid credit card number

Method ValidateCreditCard(InputValue as String) As Boolean

Var regex as New RegEx
regex.SearchPattern = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14})$"

Return regex.Search(InputValue) <> Nil 

A valid Mastercard

Method ValidateMastercard(InputValue As String) As Boolean

Var regex as New RegEx
regex.SearchPattern = "^5[1-5][0-9]{14}$"

Return regex.Search(InputValue) <> Nil 

A valid Visa number

Method ValidateVisaCard(InputValue As String) As Boolean

Var regex as New RegEx
regex.SearchPattern = "^4[0-9]{12}(?:[0-9]{3})?$"

Return regex.Search(InputValue) <> Nil 

E-mail

Method ValidateEmail(sEmail as String) As Boolean

Var emailRegex As New RegEx
emailRegex.SearchPattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"

Return emailRegex.Search(sEmail) <> Nil

URL

Method ValidateURL(sURL As String) As Boolean

Var regex As New RegEx
regex.SearchPattern = "^(https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?$"

Return regex.Search(sURL) <> Nil 
7 Likes

Just so you know… Amex cards typically start with a 3 and only have 15 numbers.

Us Europeans don’t use Amex that much, but if this is the criteria as you wrote above (plus I checked this, Trellix Doc Portal), then something like this using RegEx should work (not tested, just typing this here) :

Method ValidateAmexCard(InputValue As String) As Boolean
  Var regex As New RegEx
  regex.SearchPattern = "^3[47][0-9]{13}$" 

  Return regex.Search(InputValue) <> Nil
2 Likes

In in the UK and use Amex all the time. Its the only card that provides Avios (Air Miles).

1 Like

My Discover starts with 6.

1 Like

Validation should also include checking the checksum digit:

2 Likes

Thank you for the contribution.

1 Like

Although Amex only has 15 digits in the number it has 4 digits in the “CV2” equivalent. CV2 is the 3 digit number on the back of the card. On Amex the 4 digit number is printed on the front of the card (not embossed). Confusingly it also has a 3 digit number on the back, which isn’t used for verification.

In both cases the 15 digits + 4 and 16 digits + 3 add up to the same 19 overall digits.

1 Like