0

I have the following pattern to validate a password form (not ideal, I know, but it’s for an assignment).

/^(?=[a-zA-Z0-9]{8,})(?=[a-zA-Z]*[0-9][a-zA-Z]*$)[a-zA-Z0-9]+$/

My idea is, I need the password to be at least 8 letters long, and include at least one number and one letter. It also cannot include any special characters.

It accepts password1 as a password, but it does not accept password12 as a password. How can I fix this?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/) may help you. – ctwheels Apr 05 '18 at 20:58
  • Why do you need the `(?=[a-zA-Z]*[0-9][a-zA-Z]*$)`? It means that the whole password must contain exactly one digit between any number of letters from start to finish. – Sebastian Simon Apr 05 '18 at 20:58
  • Try `^(?=\D*\d)(?=[^a-zA-Z]*[a-zA-Z])[a-zA-Z\d]{8,}$` – ctwheels Apr 05 '18 at 20:59
  • Thanks for the link ctwheels, i'm aware of this but it's for a bit of coursework where the submission needs to include a password that is only 8 letters, include 1 digit and 1 letter but no special characters. I'm not sure Xufox, i'll remove it and test. –  Apr 05 '18 at 21:01
  • @JohnDoi2021 Don’t just remove it. Try this here: `/^(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[a-zA-Z0-9]{8,}$/`. – Sebastian Simon Apr 05 '18 at 21:01
  • that works ctwheels, i can accept your answer if you want –  Apr 05 '18 at 21:03

1 Answers1

0

Your regex is close but has some issues:

The portion (?=[a-zA-Z]*[0-9][a-zA-Z]*$) means “assert that exactly one digit ([0-9]) exists from start to finish ($) with any number of letters around it (2× [a-zA-Z]*)”.

Instead, you want something like this:

/^(?=[a-zA-Z]*[0-9])(?=[0-9]*[a-zA-Z])[a-zA-Z0-9]{8,}$/

Here, (?=[a-zA-Z]*[0-9]) and (?=[0-9]*[a-zA-Z]) mean “assert that a digit exists after any number of letters” and “assert that a letter exists after any number of digits” respectively.

After that, you can simply match [a-zA-Z0-9]{8,}.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75