Regex, detect no spaces in the string

巧了我就是萌 提交于 2019-12-12 12:47:58

问题


This is my current regex check:

const validPassword = (password) => password.match(/^(?=.*\d)(?=.\S)(?=.*[a-zA-Z]).{6,}$/);

I have a check for at least 1 letter and 1 number and at least 6 characters long. However I also want to make sure that there are no spaces anywhere in the string.

So far I'm able to enter in 6 character strings with spaces included :(

Found this answer here, but for some reason in my code it's passing.

What is the regular expression for matching that contains no white space in between text?


回答1:


It seems you need

/^(?=.*\d)(?=.*[a-zA-Z])\S{6,}$/

Details

  • ^ - start of string
  • (?=.*\d) - 1 digit (at least)
  • (?=.*[a-zA-Z]) - at least 1 letter
  • \S{6,} - 6 or more non-whitespace chars
  • $ - end of string anchor

With a principle of contrast in mind, you may revamp the pattern into

/^(?=\D*\d)(?=[^a-zA-Z]*[a-zA-Z])\S{6,}$/


来源:https://stackoverflow.com/questions/43764025/regex-detect-no-spaces-in-the-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!