3

I'm trying to add a length validation to password, but it always errors out with 'Password is too short'.

a = Artist.new(artist_name: 'Dylan', email: 'dylan@example.com', password: 'notshort')
p a.errors.full_messages  # ["Password is too short (minimum is 6 characters)"]
a = Artist.new(artist_name: 'Dylan', email: 'dylan@example.com', password: 'short')
p a.errors.full_messages  # ["Password is too short (minimum is 6 characters)"]

In the model I have

has_secure_password
validates_length_of :password, minimum: 6

If I change the validation to

validates_length_of :password, minimum: 6, allow_blank: true

The notshort password passes, but so does short.

FeifanZ
  • 16,250
  • 7
  • 45
  • 84
  • I can't replicate. `validates_length_of :password, minimum: 6` is causing `short` to error but succeeds with `notshort`. I don't have bcrypt installed so I didn't run it with `has_secure_password`. (Although `allow_blank: true` is causing them both to pass....weird) – JTG Jul 15 '14 at 21:16
  • that looks like a bug to me. what version of rails are you using? – phoet Jul 16 '14 at 02:29
  • Using Rails 4.1.4 … it does seem like a bug to me too – FeifanZ Jul 16 '14 at 14:59

2 Answers2

4

I'm using Bcrypt, too. This seems to work for me:

has_secure_password
validates :password, length: { minimum: 6, maximum: 20 }, on: :create
Cruz Nunez
  • 2,949
  • 1
  • 23
  • 33
0

Instead of validates_length_of, try just using validates like this:

validates :password, length: { minimum: 6 }

Rob Wise
  • 4,930
  • 3
  • 26
  • 31
  • Dang. Well, the issue where having `allow_blank: true` and `minimum: 6` both on at the same time doesn't make sense to me from a logic standpoint so getting a weird result like that doesn't surprise me (why would you not allow short passwords, but then allow blank passwords?). As far as the `validates_length_of` issue, I think the problem may have to do with using the `has_secure_password method` before it. Looking at the API, it apparently needs your class to also have a `:password_digest` attribute. I would comment out the `has_secure_password` line and see if the length validation works. – Rob Wise Jul 16 '14 at 22:34