Counting string length in javascript and Ruby on Rails

Posted by williamjones on Stack Overflow See other posts from Stack Overflow or by williamjones
Published on 2010-04-08T16:10:20Z Indexed on 2010/04/08 16:13 UTC
Read the original article Hit count: 274

I've got a text area on a web site that should be limited in length.

I'm allowing users to enter 255 characters, and am enforcing that limit with a Rails validation:

validates_length_of :body, :maximum => 255

At the same time, I added a javascript char counter like you see on Twitter, to give feedback to the user on how many characters he has already used, and to disable the submit button when over length, and am getting that length in Javascript with a call like this:

element.length

Lastly, to enforce data integrity, in my Postgres database, I have created this field as a varchar(255) as a last line of defense.

Unfortunately, these methods of counting characters do not appear to be directly compatible. Javascript counts the best, in that it counts what users consider as number of characters where everything is a single character. Once the submission hits Rails, however, all of the carriage returns have been converted to \r\n, now taking up 2 characters worth of space, which makes a close call fail Rails validations. Even if I were to handcode a different length validation in Rails, it would still fail when it hits the database I think, though I haven't confirmed this yet.

What's the best way for me to make all this work the way the user would want?

Best Solution: an approach that would enable me to meet user expectations, where each character of any type is only one character. If this means increasing the length of the varchar database field, a user should not be able to sneakily send a hand-crafted post that creates a row with more than 255 letters.

Somewhat Acceptable Solution: a javascript change that enables the user to see the real character count, such that hitting return increments the counter 2 characters at a time, while properly handling all symbols that might have these strange behaviors.

© Stack Overflow or respective owner

Related posts about string

Related posts about length