[SalesForce] Regex to validate Credit Card numbers

I have created a validation rule on a Log Text field, to check for Credit Card number for all major companies "(VISA, Master Card, Discover and Amex for now).

Here is the validation rule:

 NOT( REGEX( Customfield__c ,
"^(4\\d{3}([\\s\\-]?)\\d{4}\\1\\d{4}\\1\\d{4})|(5[1-5]\\d{2}([\\s\\-]?)\\d{4}\\1\\d{4}\\1\\d{4}|(6(?:011|22(?:1(?=[\\s\\-]?(?:2[6-9]|[3-9]))|[2-8]|9(?=[\\s\\-]?(?:[01]|2[0-5])))|4[4-9]\\d|5\\d\\d)([\\s\\-]?)\\d{4}\\1\\d{4}\\1\\d{4})|(3[47]\\d\\d([\\s\\-]?)\\d{6}\\1\\d{5})$"))

Problem: Its only validating the initial regex pattern for Visa card's i.e. (4\d{3}([\s\-]?)\d{4}\1\d{4}\1\d{4}) and not the rest of patterns. I reckon it has to do with the validation rule vis-a-vis the regex. Any help on validation rule structure would be greatly appreciated.

Best Answer

This is really more of a regex question than a SFDC question, so it truly belongs elsewhere in StackExchange.

However, if you know that your patterns work independently, you could change the definition of the VR to use an OR() statement instead of putting the conditionals within the regex pattern itself. This also greatly simplifies troubleshooting.

NOT( 
    OR(
        REGEX( Customfield__c , "Visa Pattern"),
        REGEX( Customfield__c , "Mastercard Pattern"),
        REGEX( Customfield__c , "Discover Pattern"),
        REGEX( Customfield__c , "AmEx Pattern")
    )
)
Related Topic