3

I'm building an app where users can create url slugs for their profile. To make sure the slugs are valid I've added a validation in the User model for slugs:

  validates :slug, :uniqueness => true, :format => { :with => /[a-z]+/ }, :allow_nil => true, :allow_blank => true

However, validation seems to pass, regardless of what format the slug string is, for example:

u.slug = 'jlskdf .jc oi/slkdjfie\*asdf&(*&*ss%&'
=> "jlskdf .jc oi/slkdjfie\\*asdf&(*&*ss%&"
u.save
=> true

Apparently it doesn't matter what I change the regex to either, everything passes. I've tried this format as well:

validates_format_of :slug, :with => /[a-z]+/

which gives the same results. Anyone have any ideas of what could be happening?

knubie
  • 231
  • 2
  • 6

1 Answers1

1

Your regular expression isn't anchored, so the pattern matches as long as it contains at least one letter a-z. Anything else is valid. Add \A and \z to the beginning and end to prevent matching any substring within the larger input.

:with => /\A[a-z]+\z/
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Ruby on Rails regular expressions [Security Guide](http://guides.rubyonrails.org/security.html#regular-expressions) now suggest you shouldn't use line start and end in validations (`^` and `$`) for this is a security threat (possible to exploit javascript). Use [string start/end](http://stackoverflow.com/questions/577653/difference-between-a-z-and-in-ruby-regular-expressions) as `\A` and `\z` instead. – Andres Feb 15 '16 at 17:23
  • @AndresEhrenpreis Yes, thank you for finding this. I've edited it. – Michael Berkowski Feb 15 '16 at 17:28