Forum: Ruby on Rails Using Value Length in Validation Message

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
phil7085 (Guest)
on 2009-05-17 13:14
(Received via mailing list)
I am learning to use Validations and am using validates_length_of to
check a field value is no longer than 240 characters.

I want to be able to produce a message back to the user telling them
that the value they entered was x characters too long.

Does anyone know how I can work with the value and its length?

validates_length_of :name, :maximum => 240, :message =>
Colin L. (Guest)
on 2009-05-17 13:52
(Received via mailing list)
:message => "Length is #{name.length}, max allowed is 240"

2009/5/17 phil7085 <removed_email_address@domain.invalid>
phil7085 (Guest)
on 2009-05-17 16:17
(Received via mailing list)
Thanks for the reply, That doesn't give me the value for name it just
gives back the name of the model. i.e Task so the length given is 4.

Any ideas?
Frederick C. (Guest)
on 2009-05-17 16:49
(Received via mailing list)
On May 17, 1:17 pm, phil7085 <removed_email_address@domain.invalid> wrote:
> Thanks for the reply, That doesn't give me the value for name it just
> gives back the name of the model. i.e Task so the length given is 4.
>
> Any ideas?

you could do this with a custom validation, ie

validates do |record|
  if ...
    record.errors.add :name, "Name is #{record.name.length} characters
long"
  end
end
Colin L. (Guest)
on 2009-05-17 17:07
(Received via mailing list)
2009/5/17 phil7085 <removed_email_address@domain.invalid>

>
>
> Thanks for the reply, That doesn't give me the value for name it just
> gives back the name of the model. i.e Task so the length given is 4.


That's true, I would go with Frederick's solution.
Colin
phil7085 (Guest)
on 2009-05-17 17:10
(Received via mailing list)
Yep that works, not quite sure why i couldn't access the length before
though, still abit over my head but i'm learning.

Thanks for your help guys.

P
This topic is locked and can not be replied to.