One way to help protect this kind of issue is to be explicit about validation steps.
This is the buggy code:
!!str.match(/^[0-9a-f]{24}$/i)
That regex is trying to do three different things: validate the length is 24, validate the string contains alphanums, and ensure the matching is pinned from start to finish.
I prefer code that makes the validation steps explicit and simpler:
the [^ part negates the characters inside the []. So it'll match anything that is NOT 0-9a-z, case insensitive /i. The !~ then says that str should not match the regex. so you end up with it saying that str should not match anything other than 0-9a-z case insensitive.
This is the buggy code:
That regex is trying to do three different things: validate the length is 24, validate the string contains alphanums, and ensure the matching is pinned from start to finish.I prefer code that makes the validation steps explicit and simpler: