Coldfusion RegEx to check strength of password
-
14-06-2021 - |
Question
I'm using this to (try) to validate a 'strong' password in ColdFusion 7.
if ( REFind("^(?=.*[A-Z])(?=.*[!@##$&*])(?=.*[0-9])(?=.*[a-z]).{6}$", myPassword, 1) EQ 0 )
However, it is failing. Can someone point out my error?
The criteria I think I'm testing is:
- 1 upper
- 1 lower
- 1 number
- 1 special char
- 6 digit min
Footnotes for non-CF people:
- the double hash is to escape the CF hash;
- ColdFusion uses Jakarta ORO 2.0.6 as its regex engine
Solution
Ok, well the set of criteria you're trying to test on are bad.
For example, Pa$5word
meets the criteria but is a bad choice, whilst my name |z NOT Fr£d
is much stronger but fails (no numbers; different symbols).
Ideally you should look for and existing password strength checker (although I've no idea if there are any existing/good ones out there).
Anyhow, for a simple solution to what you've asked, that spells out exactly what is being checked, just do:
<cfif NOT
( len(myPassword) GTE 6
AND refind('[A-Z]',myPassword)
AND refind('[a-z]',myPassword)
AND refind('[0-9]',myPassword)
AND refind('[!@##$&*]',myPassword)
)>
There is no need/benefit to smushing it all into a single regex.
OTHER TIPS
One reason why it might be failing is your business rule is "at least six characters", but your regex enforces exactly six characters.
Also: it'd be helpful it you stated which conditions it fails on. My superficial testing suggests you're fine except for the caveat I mention above. If you could finetune your question to point out what non-superficial testing that I'm not thinking about is failing, that'd be helpful.
In the real world, I'd also expect what punctuation characters you consider valid, too. Your list is a bit short. But that's nowt to do with you current problem.
Try this.
^(?=.[A-Z])(?=.[!@##\$&])(?=.[0-9])(?=.*[a-z]).{6,}$
Add comma after six since you want to allow more than 6 characters and $ must be escaped with \$
Update
Try below, ^ and $ removed from above one
(?=.[A-Z])(?=.[!@##$&])(?=.[0-9])(?=.*[a-z]).{6,}
fwiw to separate out the different character failures:
<cfscript> raRe=[["[a-z]","lowercase"],["[A-Z]","uppercase"],["[\W]","non-alphanumeric"],["[\d]","numeric"]];</cfscript>
<cfoutput>
<cfloop from=1 to=4 index="idxRe">
#idxRe#: refind(raRe[idxRe][1], myPassword):<b>#refind(raRe[idxRe][1], myPassword)#</b> myPassword:<b>#myPassword#</b>; re:<b>#raRe[idxRe][1]#</b>; <br />
<cfif refind(raRe[idxRe][1], myPassword) eq 0><b>Your password must include at least one #raRe[idxRe][2]# character</b><br /></cfif>
</cfloop>
</cfoutput>
And of course if >=6 is also required:
<cfif Len(myPassword) lte 6><b>Your password must be at least 6 characters long</b></cfif>