validatorjs / validator.js

String validation
MIT License
23.06k stars 2.3k forks source link

matches() function not working correctly!? #1768

Open vnvyvu opened 3 years ago

vnvyvu commented 3 years ago

Describe the bug I use matches() and below regex string to check strong password myRegEx = (?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,}/gm

Examples My code: https://stackblitz.com/edit/node-mub3gz or https://replit.com/join/mcrsnwazhi-vyvu

first request image 2nd request image

Additional context Validator.js version: 6.12.2 Node.js version: 16.10.0 OS platform: windows

Sorry if it's not a bug! ==> Temporarily I use isStrongPassword() instead of matches()

tux-tn commented 2 years ago

Strange behaviour, internally matches is only returning a new RegExp. Your issue may be related to the fact that your passing directly the modifiers in the regex, you are supposed to call matches this way:

str.matches(/(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,}/, 'gm');

Since you are using express-validator you may find more help there or perhaps @fedeci have an idea about this issue.

fedeci commented 2 years ago

Hey @vnvyvu, does it work if you pass a string instead of a regexp?

body('pass').matches('(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,}', 'gm')
vnvyvu commented 2 years ago

Hey @vnvyvu, does it work if you pass a string instead of a regexp?

body('pass').matches('(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W]).{8,}', 'gm')

yea, i tried and it worked!

fedeci commented 2 years ago

It has to be fixed for Regex objects however.

fedeci commented 2 years ago

Yeah, that happened to me too some times ago but never had a change to investigate it properly. I can't reproduce it in express-validator unit testing. It will be fixed as soon as I implement integration tests.

tux-tn commented 2 years ago

Is the problem related to express-validator? Can i close this issue?

fedeci commented 2 years ago

I'm not sure, but I assume it is.

fedeci commented 2 years ago

Found this comment: https://github.com/express-validator/express-validator/issues/1127#issuecomment-1026730522

Apparently pattern.test(str) is unreliable when preserving the same instance of a regex object, instead str.match(pattern) is. @tux-tn would a PR to change that method in this repo be accepted? We are already working on a fix on express-validator but an "upstream one" would be great!

wyatt-substack commented 2 years ago

Should either use .match or set pattern.lastIndex = 0; before calling .test.

braaar commented 2 years ago

Similar issue experienced downsteam in class-validator, as well https://github.com/typestack/class-validator/issues/1707