How to create groups in regex to validate password criteria in Elixir?

Asked

Viewed 205 times

3

I need to validate the criteria in a password:

  • It must contain at least one capital letter.
  • At least one tiny
  • At least one number
  • The size should be between 6 and 32 characters
  • May not have any special character or space
  • It should have all 3 types: uppercase, lowercase and numbers, no matter the order

I tried several ways, I took a look at the documentation of regex (Elixir and Perl), but I stuck here:

Regex.run(~r/^[A-Z](?=.*)[a-z](?=.*)[^\W_]{5,30}$/,IO.gets"")

But this regex only allows the password starting with uppercase and does not allow numbers if I add something like \d(?=.*) or [0-9](?=.*) nothing else works.

As an example in ES/JS it would be: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[^\W_]{6,32}$/

  • 1

    This example in Js is correct. This is a question or an answer?

  • The example in JS is correct, works for all criteria and independent of the order of the items. It is a question, fix the title.

1 answer

3


To create the desired expression, you must use the Positive Lookaheads ((?=...)), as you may have noticed. However, you are using it incorrectly. To add criteria without a specific order, your lookaheads must be present before the validated text.

Example 1:

/(?=a).../
Corresponde com:
abc, acb
Não corresponde com:
bca, cba

With that in mind, to make the place that the letter a appears to be irrelevant, add .* before and after the criterion sought.

Example 2:

/(?=.*a.*).../
Corresponde com:
abc, acb, bca, cba

Now it only remains to add other groups with the necessary criteria, being them:

(?=.*[a-z].*) - Requires at least one lower case letter
(?=.*[A-Z].*) - Requires at least a capital letter
(?=.*[0-9].*) - Requires at least one number

And the rest needed to match:

[a-zA-Z0-9]{6,32} - 6 to 32 characters valid for your password (which can also be reduced to: (?:\w|\d){6,32}).

Here’s your full expression:

/^(?=.*[a-z].*)(?=.*[A-Z].*)(?=.*[0-9].*)[a-zA-Z0-9]{6,32}$/

Check out the results here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.