Search code examples
ruby-on-railsregexrubyruby-on-rails-5

error in password validation with regex in ruby


I'm trying to validate the devise password for my ruby on rails 6 application. It works perfectly but when I add the "/" sign inside the allowed signs it shows me the following error:

/app/models/user.rb:26: premature end of char-class: /(?=.{8,})(?=.?[A-Z])(?=.?[a-z])(?=.?[0-9])(?=.[$#/ /home/jeff/Desktop/medic/app/models/user.rb:26: syntax error, unexpected ']', expecting ')' ...?[a-z])(?=.?[0-9])(?=.[$#*/])^[^&|]+$/)

my validation has restrictions for the user to enter at least one lower case, one upper case, one number, signs like $#*/ and excluding signs like |&

this is my validation:

  validate :password_uppercase
  def password_uppercase
    return if !!password.match(/(?=.{8,})(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*[$#*/])^[^&|]+$/)
    errors.add :password, ' password dont match'
  end

Solution

  • Your problem is really just a typo, but a tricky one, worth pointing out. You need to escape the forward slash in the final lookahead's character class:

    password.match(/(?=.{8,})(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*[$#*\/])^[^&|]+$/)
    #                                                                     ^^^ change is here
    

    This is because you have specified / as the delimiter in the call to match.