简体   繁体   中英

JavaScript regular expression returns false, but regex tester returning true

I have a JavaScript regular expression that I'm using for frontend password validation in an input field. Here is what my input field looks like:

<input type='password' placeholder='Password...' id='password' pattern='^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})' required>

That regular expression is looking for a string: eight characters or longer, with an uppercase letter, lowercase letter, number, and a special character. Let's take the string: November2017! for instance. That should pass the regular expression, but it doesn't in my webapp. And when I copy and paste the regular expression from my input field ^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,}) and put it into regex101.com, that string passes the validation. But it does not pass the validation in my webapp. Is there a specific reason why putting it in a pattern attribute would change whether or not it would pass validation?

You need to add the .{8,} in the end.

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*]).{8,}

It happens because the pattern must match the complete string, and your current expression only matches the beginning of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM