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

2

I need to validate the criteria in a password:

  • Must contain at least one uppercase letter.
  • At least one lowercase
  • At least one number
  • Size must be between 6 and 32 characters
  • Can not have any special characters or spaces
  • Must have all 3 types: uppercase, lowercase and numbers, no matter the order

I tried several ways, I took a look at the regex documentation (Elixir and Perl), but I locked it 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 would be: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)[^\W_]{6,32}$/

    
asked by anonymous 22.07.2017 / 12:29

1 answer

3

To create the searched expression, you should use the Positive Lookaheads ( (?=...) ), as you may have already 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 this in mind, to make the place that the letter a appears to be irrelevant, add .* before and after the search criteria.

Example 2:

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

Now all you have to do is add other groups with the required criteria, which are:

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

And the rest needed to combine:

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

Here is your complete expression:

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

Check out the results here .

    
27.07.2017 / 23:16