Blog Archives

Validate Credit Card Numbers with Regular Expressions

Expressions below account for IIN numbers on CC’s of most major US issuers which includes validating starting character. These should be used in addition to Luhn Algorithm mod10 check.

These expressions can be used on clientside and codebehind to give your end users notification of invalid entry without wasting resources on a failed/invalid post. See snippet below. Expressions should technically be cross-platform.

Note: although very similar to those found on, there are some small differences which do not account for the old standards in my examples since these cards are no longer in circulation.


string vs = @"((^4)[0-9]{15}$)|";
            string mc = @"((^5[1-5])[0-9]{14}$)|";
            string ax = @"((^3[4|7])[0-9]{14})$|";
            string ds = @"(^6(011|5[0-9]{2})[0-9]{12}$)";

string expirationmonth = @"((^[0-9]$)|(^[0-9][0-2]$))";

string ordertotalamount = @"((^[0-9]{1,5}$)|(^[0-9]{1,5}\.[0-9]{1,2}$))"; //does not account for currency symbols

System.Text.StringBuilder sbexp = new System.Text.StringBuilder();
            for (int i = 0; i <= 20; i++) //create list of years from now+20. same range amazon uses for card
                sbexp.Append("(^" + (DateTime.Now.Year + i).ToString() + "$)|");
                if (i < 20) //don't append or on last
                    sbexp.Append((DateTime.Now.Year + i).ToString());

            ((RegularExpressionValidator)validator).ValidationExpression = sbexp.ToString();

((RegularExpressionValidator)validator).ValidationExpression = vs+mc+ax+ds;

Wikipedia (IIN numbers),
Wikipedia (Luhn Algorithm),,

Quick Regex Reference

Commonly Used:

 private bool ValidTLD(string tld)
        string[] validtlds = {"com","org","net","edu","gov","mil","biz","info","mobi","name","aero","asia","jobs","museum"};
        if (validtlds.Contains(tld.ToLower().Replace(".",""))) {
            return true;

        return false;

if (!ValidTLD(System.Text.RegularExpressions.Regex.Match(tbNewEmailAddress.Text, @"^\w+([-+.']\w+)*@.*(\.\w+)$").Groups[2].Value))
            hlnkReturn.Visible = false;
            tblSuccess.Visible = false;
            tblError.Visible = true;
            pnlMessages.Visible = true;
            lblErrorMessage.Visible = true;
            lblErrorMessage.Text = "Invalid domain specified. Please contact support if you continue to receive this message.";   

Get Top Level Domain of Email:

//ex. for or returns ".com"
string regextld = @"^\w+([-+.']\w+)*@.*(\.\w+)$";
if (System.Text.RegularExpressions.Regex.IsMatch(tbNewEmailAddress.Text, regextld))
            System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(tbNewEmailAddress.Text, regextld);
                return m.Groups[2].Value;