Posted on by

Limit the Amount of Text in a Text Area or Rich Text Form Element

Participants Database has two form elements for large blocks of text. In some cases, you will want to limit the number of characters your users can input. This is fairly simple to do on the frontend by using the HTML5 “maxlength” attribute. The maxlength attribute prevents any input to a textarea (or other input) beyond a set number of characters, so we can use this to easily limit the size of the text the user can submit.

Limiting the Text-Area Element

For a “Text Area” element, this is very simple. We just need to add the maxlength attribute to the “values” parameter in the field definition on the Manage Database Fields page. If you wanted to limit the length of the text to 200 characters, you would use “maxlength::200” for your attribute, like this:

In fact, the “maxlength” attribute can be used on regular text elements as well.

Limiting Input to a Rich Text Field

For a “Rich Text” field, the process is somewhat more complex because we need to use some javascript to place the maxlength attribute. First, set up a custom template (read the linked article for a guide on how to do that) and then in that custom template, you can put some very simple javascript that places the maxlength attribute.

To create the javascript, you need to know two things: the number of characters you want to limit the input to and the name of the field. The name of the field is used to target the specific rich text field that needs limiting…so, for instance, if the name of your field is “my_story” the ID of the text area will be “pdb_my_story” The plugin adds the “pdb_” prefix so that it won’t conflict with other IDs on the page.

In your template, you can put the javascript in after the ?> and before the <div

near the top of the template. Here is your example, but remember you have to change the field ID (which is “#pdb_my_story” in this example) and number of characters to be correct for your situation.

<script> 
jQuery(function($){
   $('#pdb_my_story').attr('maxlength','200');
} ); 
</script>

Limiting the Size on the Backend

These techniques are very simple and effective, but they can be bypassed by savvy users on the frontend. If you want to make absolutely certain that longer blocks of text can’t be submitted, you need to enforce it on the backend as well. This is most easily done with a “regex” validation setting.

To limit the number of characters using a regex, select “regex/match” as the validation type, then use a regex like this to set the limit:

That pattern will only allow an input of between zero and 200 characters.

Leave a Reply
You have to agree to the comment policy.

Leave a Reply
You have to agree to the comment policy.