0

I'm looking for a regex for my JavaScript password function which checks that the user's password is at least 8 characters long with at least 1 number in it.

Thank you!

terpak
  • 1,131
  • 3
  • 17
  • 35
  • 2
    What have you tried.......? *edit:* [have a hoon on this online tester](http://regex101.com/), it'll teach you everything you need to know. – scrowler Jul 09 '14 at 02:05
  • 3
    What kind of characters? Is the Thai alphabet acceptable? – zx81 Jul 09 '14 at 02:06
  • 1
    You can just use `.length > 8` for the length being 8 or more characters. And `.match(/[0-9]/).length > 0` for checking if there are numbers. – mash Jul 09 '14 at 02:07
  • My knowledge of writing regular expressions is completely nada, so throughout my googling and regex generator tool usage, I couldn't manipulate the regex to fit these criteria. Basically, I've tried a bunch of irrelevant solutions. – terpak Jul 09 '14 at 02:07
  • 1
    @Mash Use `\d` instead of `[0-9]` for extra eliteness ;-) – Ja͢ck Jul 09 '14 at 02:07

1 Answers1

13
/^(?=.*\d).{8,}$/

(?=.*\d) Asserts that a digit is anywhere within the string.

.{8,} Asserts that the entire string is a composition of at least 8 "anything, except new line".

View an online regex demo.

Unihedron
  • 10,902
  • 13
  • 62
  • 72
  • This regex nearly works for most use-cases, but it also matches strings that only have numbers. Is there a way, where we could also enforce at least 1 letter? – lucbas Jul 28 '20 at 14:23
  • 1
    @lucbas add `(?=.*[a-zA-Z])`: `/^(?=.*\d)(?=.*[a-zA-Z]).{8,}$/` – Unihedron Aug 16 '20 at 06:24