0

I've built a User model and sign up along the lines of Michael Hartl's tutorial. I have adapted this regex for minimum password complexity to check for

  • at least one lower case letter
  • at least one upper case letter
  • at least one number
  • at least one symbol

i.e.

^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$

The regex works perfectly as intended in rubular, however, I have not been able to successfully implement it in my app

What I've tried so far

I've tried various combinations of

  VALID_PASSWORD_REGEX = ^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$

  validates :password, format: { with: VALID_PASSWORD_REGEX }

With and without:

  • double quotations around the regex e.g. "^(?=.* ... {8,}$"
  • forward slashes around /VALID_PASSWORD_REGEX/
  • the # in the [!@#$&*] part of the regex ('#' seems to be recognised as a comment in sublime text)

I keep getting errors along the lines of "A regular expression or a proc or lambda must be supplied as :with" and "syntax error, unexpected '^'"

What worked

After reading assefamaru's answer, I was able to see the ^ and $ needed to be replaced with \A and \z (see here)

Here's what works:

  VALID_PASSWORD_REGEX = /\A(?=.*[A-Z])(?=.*[!@$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$\z/
  validates :password, format: { with: VALID_PASSWORD_REGEX }
stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

2

As stated in ruby's docs, regexps are created using the /.../ and %r{...} literals, and by the Regexp::new constructor. For example, you can have:

VALID_PASSWD = /^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$/

or

VALID_PASSWD = %r(^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$)

or

VALID_PASSWD = Regexp.new("^(?=.*[A-Z])(?=.*[!@#$&*])(?=.*[0-9])(?=.*[a-z]).{8,}$")

Then, you can have the validation:

validates :password, format: { with: VALID_PASSWD }

Ps. In your rubular link, you might have noticed the forward slashes present to the left and right of the text-box containing the regex. This corresponds to the /.../ literal for creating regexps.

assefamaru
  • 2,751
  • 2
  • 10
  • 14