views:

328

answers:

2

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.

+1  A: 

I'd recommend storing data with CR-LF converted to single LF. Get rid of rails verification, as this is unneeded when database field has set width. Instead make Rails convert CRLF to LF before storing.

Tometzky
But is CR-LF the only special character I need to watch out for, or could there be other things that trigger this? Also, the Rails verification is still needed so that nice messages can be displayed to the user on problems.
WIlliam Jones
If you have set both database and a HTML to UTF-8 encoding then you should not have any other problems. Forget nice messages, as they will never be displayed - your client side JavaScript will not allow to submit too long data. For 0,01% of users with JavaScript disabled it is not worth it.
Tometzky