Archive

Posts Tagged ‘max-length textarea’

Enforcing Max-Length on a textarea

October 5th, 2009 No comments

Lets say you have a textarea in which you will only be saving the first 300 characters the user puts in there. You likely have a database field of type varchar(300), and a small space to fit the user input into that makes a long text input not feasible. You could let the user type in whatever s/he wants, and then be disappointed to find that only the first bit of their epic novel was saved. Likely your users will call your site buggy and find some other website to play with, because your lazy handling of their input did not have their needs in mind. The user must be informed that their input will be truncate at 300 characters.

To handle this situation you need a multi-line text input, that enforces a 300 character limit. If the user types more than 300 characters, the extra characters shouldn’t show up so that s/he knows that only what they can see displayed will be saved. For the multi-line requirement, you have to use a textarea, but textarea’s do not have a built in max-length directive like the one line text inputs do. So, we have to make out own. I went looking for a solution today, and found a rather handsome, one liner solution over at psacake. Sadly though this solution is serverly flawed, to a degree in which I would say it’s unusable. The psacake solution stops the user from inputting more than 300 characters, but it also prevents the user from using the backspace to change their input. I have updated psacake’s solution to give the user a chance to chance to edit what they have written after they discover the textarea has a character limit imposed upon it.

function imposeMaxLength(event, object, MaxLen){
    var key = event.keyCode ? event.keyCode : event.which;
    if(key == 8){
        // 8 is the keycode for the backspace key
        return true;
    }else{
        return (object.value.length <= MaxLen);
    }
}

Then, call they function like this:

<textarea onkeypress='return imposeMaxLength(event, this, 300);'></textarea>

Please feel free to use this code on your site. It has passed my tests on both Firefox and IE8.