Limiting the Length of Text Fields

Problem

I have a text field in my app, and I want to limit the number of characters someone can type into it.

Solution

You’re looking for a combination of getValue() and setValue(), a pair of getter/setters implemented by Facebook as a shortcut to manipulating the value of various object types. If your Canvas page is set up something like this:

<div id="message">
    <textarea id="messageField" onkeyup="limitLength(this,200);"></textarea>
    <div id="messageCount">0/200 characters</div>
</div>

then give this a shot:

function limitLength(targetField,maxLength){
    var currentLength = targetField.getValue().length;

    if( currentLength > maxLength){
        targetField.setValue(targetField.getValue().substring(0, maxLength));
        currentLength = maxLength;
    }

    document.getElementById('messageCount').setTextValue(currentLength + '/200
        characters');
}

Discussion

There are lots of occasions in which you might need to do something like limit the length of a text field, so it’s always better to try to write functions like that as general-purpose utilities rather than one-time-use tools. That function could have been written as checkMessageField() without passing in the field or length, but then you’d also need checkProfileField() and checkDescriptionField(), etc. Since FBJS allows you to include external JavaScript files, do yourself a favor and put things like this into a utilities.js, which you can just include in pages where you need them (see Linking to External FBJS Files).

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.