US and Canadian SSN Checking with CF Regex

US and Canadian SSN Checking with CF Regex

ColdFusion Regex is a based on Perl Regex WITH exceptions so it is a bit odd. It would be nice if it were the same as JavaScript and then it would be simple for front end and backend processes to share regex patterns. Aside from that, CFDocs doesn't have a very good documentation. So unless you know PERL regex, the examples in ColdFusion make it appear limited. I saw no examples on the 8 or so pages that suggested anything like being able to use the carat or what pattern keys were available other than simple a-z and 0-9.

I needed to clean any non-numbers out of a social security number. Given CFDocs level of documentation, and since I needed negative logic of the simple 0-9 (essentially, replace anything NOT equivalent to 0-9), I at first I thought I was going to have to do this:

This really bothered me because it did not necessarily catch all non-numbers (I just went down the keyboard really quickly), and it was cumbersome looking.

So I went ahead and tested the JavaScript pattern equivalents and these ALL worked fine in ColdFusion 8. I should have just tried that first and am actually surprised I have never had to do this on the back-end before now.

My test case in CFScript:

Now, the bigger picture here is previously, I had a form that had the SSN broken into 3 parts for US styled SSN. However, client needed to start adding Canadian style SSN which, happily, is still 9 digits, but follows a XXX-XXX-XXX pattern instead of the US XXX-XX-XXXX pattern.

Originally, my mind set was a "If Fail -> User needs to fix this" cycle. This new aspect made me think of it more in lines of multi-pattern phone masks where you take whatever the user types and make the best of it. So I knew I could do this in Javascript but I wanted front-end to match back-end validation as well so the DAO (data access object) would have this same validation logic no matter how the data got to it without relying on the end-user interface to pre-validate.

So instead of simply validating by len() and isNumeric(), putting them together with a hyphen and then isValid('ssn', x) on a three field form, I needed to use a 11 char space single field form, strip that down to digits, and then add checking based on State and Province codes and then format correctly for each country respectively no matter how the user typed it in.