1

I'm finding a regular expression which adheres below rules.

Acceptance criteria: Password must contain a combination of letters, numbers, and at least a special character.`

Here is my Regex:

validates :password, presence: true,
format: { with: ^(?=[a-zA-Z0-9]*$)([^A-Za-z0-9])}

I am not all that great at regex, so any and all help is greatly appreciated!

Allan
  • 12,117
  • 3
  • 27
  • 51
CADAVID
  • 93
  • 1
  • 2
  • 9

1 Answers1

4

You can use the following RegEx pattern

/^(?=.*\d)(?=.*([a-z]|[A-Z]))([\x20-\x7E]){8,}$/

Let's look at what it is doing:

(?=.*\d) shows that the string should contain atleast one integer.
(?=.*([a-z]|[A-Z])) shows that the string should contain atleast one alphabet either from downcase or upcase.
([\x20-\x7E]) shows that string can have special characters of ascii values 20 to 7E.
{8,} shows that string should be minimum of 8 characters long. While you have not mentioned it should be at least 8 characters long but it is good to have.

If you're unsure about the ASCII values, you can google it or you could use the following instead:

  /^(?=.*\d)(?=.*([a-z]|[A-Z]))(?=.*[@#$%^&+=]){8,}$/

As suggested in the comments, a better way can be:

/\A(?=.*\d)(?=.*([a-z]))(?=.*[@#$%^&+=]){8,}\z/i

Here:

\A represents beginning of string.
\z represents end of string.
/i represents case in-sensitive mode.

P.S: I have not tested it yet. May be I'll test and update later if required.

Manoj Monga
  • 3,033
  • 14
  • 19
  • Nice answer! you can improve this regex by putting it in insensitive case and remove `|[A-Z]` use `i` attribute – Allan Mar 09 '18 at 06:15
  • You almost always want `\A` and `\z` instead of `^` and `$` in Ruby, `^` and `$` are beginning/ending of *line* whereas `\A` and `\z` are beginning/ending of *string*. – mu is too short Mar 09 '18 at 06:15
  • Do you mean this: `/\A(?=.*\d)(?=.*([a-z]|[A-Z]))(?=.*[@#$%^&+=]){8,}\z/i` ? – Manoj Monga Mar 09 '18 at 06:23