Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple rails format validation not firing

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?

like image 317
knubie Avatar asked Dec 30 '25 12:12

knubie


1 Answers

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/
like image 169
Michael Berkowski Avatar answered Jan 02 '26 02:01

Michael Berkowski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!