Question

I'm trying to create a regular expression in javascript for a UK bank sort code so that the user can input 6 digits, or 6 digits with a hyphen between pairs. For example "123456" or "12-34-56". Also not all of the digits can be 0. So far I've got /(?!0{2}(-?0{2}){2})(\d{2}(-\d{2}){2})|(\d{6})/ and this jsFiddle to test.

This is my first regular expression so I'm not sure I'm doing it right. The test for 6 0-digits should fail and I thought the -? optional hyphen in the lookahead would cause it to treat it the same as 6 0-digits with hyphens, but it isn't. I'd appreciate some help and any criticism if I'm doing it completely incorrectly!

Was it helpful?

Solution

Just to answer your question, you can validate user input with:

/^(?!(?:0{6}|00-00-00))(?:\d{6}|\d\d-\d\d-\d\d)$/.test(inputString)

It will strictly match only input in the form XX-XX-XX or XXXXXX where X are digits, and will exclude 00-00-00, 000000 along with any other cases (e.g. XX-XXXX or XXXX-XX).

However, in my opinion, as stated in other comments, I think it is still better if you force user to either always enter the hyphen, or none at all. Being extra strict when dealing with anything related to money saves (unknown) troubles later.

OTHER TIPS

Since any of the digits can be zero, but not all at once, you should treat the one case where they are all zero as a single, special case.

You are checking for two digits (\d{2}), then an optional hyphen (-?), then another two digits (\d{2}) and another optional hyphen (-?), before another two digits (\d{2}).

Putting this together gives \d{2}-?\d{2}-?\d{2}, but you can simplify this further:

(\d{2}-?){2}\d{2}

You then use the following pseudocode to match the format but not 000000 or 00-00-00:

if (string.match("/(\d{2}-?){2}\d{2}/") && !string.match("/(00-?){2}00/"))
     //then it's a valid code, you could also use (0{2}-?){2}0{2} to check zeros

You may wish to add the string anchors ^ (start) and $ (end) to check the entire string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top