If you need to limit the maximum length of comments posted by site visitors/members, this mini module will do the job. Save as file 'limit_comments.module' without the ending ?> tag, and activate as usual from the /admin/modules page. The new setting for maximum comment length will be accessible on the existing comments configuration page at /admin/comment/configure.

Drupal 6.x

Comments are different in drupal 6, they are set on content type, so we need different code, here is my suggestion :

<?php
// Must work on Drupal 6
function limit_comments_help($path, $arg) {
  switch ($path) {
    case 'admin/modules#description':
      return t('Enforce a maximum comment length');
    case 'admin/help#limit_comments':
      $output = t('This module enforces a maximum limit on the length of comments posted by non-administrators.  To change the maximum comment length, visit each <a href="%url">content type</a> and set comment parameters to your needs.', array('%url' => url('admin/content/types')));
      return $output;
  }
}

function limit_comments_validate($node, &$form) {
  // we set up variable by content type, so we need to get content type
  $node = node_load($node['nid']['#value']);
  $max = variable_get('comment_max_length_'.$node->type, 1000); 
  if (strlen(trim($form['values']['comment'])) > $max) {
    form_set_error('comment', t('Your comment is too long. Comments are limited to a maximum of %num characters.', array('%num' => $max)));
  }
}

/**
* Implementation of hook_form_alter().
*/
function limit_comments_form_alter(&$form, $form_state, $form_id) {
  // comment form
  if ($form_id == 'comment_form') {
    $node = node_load($form['nid']['#value']); // we load node to get content type
    $form['#validate'] = array('limit_comments_validate');
    $form['comment_filter']['comment']['#description'] = t('Comments are limited to a maximum of %num characters.', array('%num' => variable_get('comment_max_length_'.$node->type, 0)));
  }
  // content type form
  elseif ($form_id == 'node_type_form' && isset($form['identity']['type'])) {
    $form['comment']['comment_max_length'] = array(
      '#type' => 'select',
      '#title' => t('Maximum comment length'),
      '#default_value' => variable_get('comment_max_length_'. $form['#node_type']->type, 1000), // we set variable for each content type
      '#options' => drupal_map_assoc(array(300, 500, 700, 1000, 1500, 2000, 2500, 3000, 5000)),
      '#description' => t('Maximum permitted length of a comment (in characters) for non-administrators.'),
      '#weight' => -1,
    );
  }
}
?>

Drupal 5.x

Note: for D5 you also need to create a modules/limit_comments/limit_comments.info file per http://drupal.org/node/126743

// Tested with Drupal 5.2
function limit_comments_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Enforce a maximum comment length');
    case 'admin/help#limit_comments':
      $output = t('This module enforces a maximum limit on the length of comments posted by non-administrators.  To change the maximum comment length, visit the <a href="%url">comments configuration page</a>.', array('%url' => url('admin/comment/configure')));
      return $output;
  }
}

function limit_comments_validate($form_id, $form_values) {
  $max = variable_get('comment_max_length', 1000);
  if (strlen(trim($form_values['comment'])) > $max) {
    form_set_error('comment', t('Your comment is too long. Comments are limited to a maximum of %num characters.', array('%num' => $max)));
  }
}

function limit_comments_form_alter($form_id, &$form) {

  if ($form_id == 'comment_form' && !user_access('administer comments')) {
    $form['#validate']['limit_comments_validate'] = array();
    $form['comment_filter']['comment']['#description'] = t('Comments are limited to a maximum of %num characters.', array('%num' => variable_get('comment_max_length', 1000)));
  }
  elseif ($form_id == 'comment_admin_settings') {

    $form['comment_max_length'] = array(
      '#type' => 'select',
      '#title' => t('Maximum comment length'),
      '#default_value' => variable_get('comment_max_length', 1000),
      '#options' => drupal_map_assoc(array(300, 500, 700, 1000, 1500, 2000, 2500, 3000, 5000)),
      '#description' => t('Maximum permitted length of a comment (in characters) for non-administrators.'),
      '#weight' => -1,
    );  
  }
}

Drupal 4.7

// Tested with Drupal 4.7.4
function limit_comments_help($section) {
  switch ($section) {
    case 'admin/modules#description':
      return t('Enforce a maximum comment length');
    case 'admin/help#limit_comments':
      $output = t('This module enforces a maximum limit on the length of comments posted by non-administrators.  To change the maximum comment length, visit the <a href="%url">comments configuration page</a>.', array('%url' => url('admin/comment/configure')));
      return $output;
  }
}

function limit_comments_validate($form_id, $form_values) {
  $max = variable_get('comment_max_length', 1000);
  if (strlen(trim($form_values['comment'])) > $max) {
    form_set_error('comment', t('Your comment is too long. Comments are limited to a maximum of %num characters.', array('%num' => $max)));
  }
}

function limit_comments_form_alter($form_id, &$form) {

  if ($form_id == 'comment_form' && !user_access('administer comments')) {
    $form['#validate']['limit_comments_validate'] = array();
    $form['comment_filter']['comment']['#description'] = t('Comments are limited to a maximum of %num characters.', array('%num' => variable_get('comment_max_length', 1000)));
  }
  elseif ($form_id == 'comment_settings_form') {
    $form['comment_max_length'] = array(
      '#type' => 'select',
      '#title' => t('Maximum comment length'),
      '#default_value' => variable_get('comment_max_length', 1000),
      '#options' => drupal_map_assoc(array(300, 500, 700, 1000, 1500, 2000, 2500, 3000, 5000)),
      '#description' => t('Maximum permitted length of a comment (in characters) for non-administrators.'),
      '#weight' => -1,
    );    
  } 
}

Comments

wwwoliondorcom’s picture

Hi, do you have a demonstration website where you use this module ?

Thanks.

giorgio79’s picture

Hello,

I would like to do the oposite, namely enforce a minimum lenght.

Cheers,
G

nmridul’s picture

Here is a thread for this exact requirement. I hope someone can respond on how to set a minimum number of characters for the comments.

http://drupal.org/node/452166

ekrispin’s picture

How could I do the same Max/min restrictions but on the title of the comment?

As If’s picture

The form_alter() function above didn't work for me under D6. Here is a modified version that did...

function limit_comments_form_alter($form_id, &$form) {
  // comment form
  if ($form_id['#id'] == 'comment-form') {
    $form_id['preview']['#type']='hidden';
    $node = node_load($form['nid']['#value']);
    $form_id['#validate'][] = 'limit_comments_validate';
    $form_id['comment_filter']['comment']['#description'] = t('Comments are limited to a maximum of %num characters.', array('%num' => variable_get('comment_max_length_'.$node->type, 1000)));
  }
  // content type form
  if ($form_id['#id'] == 'node-type-form' && $form['post']['op'] != 'Save content type') {
    $form_id['comment']['comment_max_length'] = array(
      '#type' => 'select',
      '#title' => t('Maximum comment length'),
      '#default_value' => variable_get('comment_max_length_' . $form_id['#node_type']->type, 1000),
      '#options' => drupal_map_assoc(array(300, 500, 700, 1000, 1500, 2000, 2500, 3000, 5000)),
      '#description' => t('Maximum permitted length of a comment (in characters) for non-administrators.'),
      '#weight' => -1,
    );
  }
}

NOTE: The above "module" does not update the value once it is set, because variable_set() is never used. IOW, once the content type is created with a given comment limit value, that's the value it will remain unless changed directly in the variables table (via PHPMyAdmin or whatever).

-------------------------------------------
Interactive Worlds and Immersive Obsessions
http://www.asifproductions.com

djudd’s picture

I've put this module in place, but I'm having one problem.

I can't even set a variable. When I go in through PHPMyAdmin, I don't see any variables that match up correctly. There is no comment_max_length_story variable, for example.

So if I set a length of 2,000 characters for a story comment, and save the content type, when I go back in, it's back to 1,000.

I tried creating the variable manually and setting it, but that did nothing either.

As If’s picture

Don't know if your content type was created already or not, but using PHPMyAdmin you can just try inserting the variable directly into the variables table. The command variable_get('comment_max_length_'.$node->type, 1000)) is saying "go get this variable, and if you don't find it, return 1000". That's probably why you're getting 1000 again (if I understand you correctly).

-------------------------------------------
Interactive Worlds and Immersive Obsessions
http://www.asifproductions.com

marcvangend’s picture

@As If: your revision for D6 might happen to work, but it's definately not the correct way to do it because hook_form_alter takes three arguments in D6 (&$form, $form_state, $form_id). See http://api.drupal.org/api/function/hook_form_alter/6.

As If’s picture

You're right, Marc. It's a relic of some D5 code that got mixed in with D6 code. Frankly I'm actually a little amazed that it works ;-) but it does. On a D6 production site with massive traffic. Guess I should rewrite it though, just to stick with the program.

EDIT FOR CLOSURE: The original code (with some trivial variations) now works for me too. My problem was the arguments to the function, which I seem to have inherited from the D5 version. Anyway, for those following along... My version of the function managed to get around the missing third argument by using $form['#id'] instead of $form_id (which otherwise would have come from the third variable). I figured it out by putting this at the top of the function and examining the output:

function zzz_form_alter(&$form, $form_state, $form_id) {
// DEBUGGING
echo $form_id . '<br>';
echo "<textarea cols=100 rows=30>";
print_r($form);
echo '</textarea>';
// END DEBUGGING
...

Maybe that can help someone else while they're debugging forms. We now return you to your regularly-scheduled programming!

-------------------------------------------
Interactive Worlds and Immersive Obsessions
http://www.asifproductions.com

marcvangend’s picture

Thanks for the explanation, I already guessed something like that would have happened. In case anyone likes to know: the code in the original post works fine for me.

Some bonus javascript:
I wanted a way to inform the user about the number of characters used while typing, so I put this javascript in my page (see the Javascript Startup Guide if you don't know how to do that).

var description = $('#comment-form .description').html() + ' ';
if (description) {
  $('#edit-comment').keyup( function() {
      var charCount = $(this).val().length;
      $('#comment-form .description').html(description + Drupal.t('You have used !count characters.', { '!count': charCount }));
  });
}
Rosamunda’s picture

hi!
Thanks for the upgrade on this code, because I think it´s no use if you linit the character cpount, but don´t tell your users how many characters they have left.
The thing is that I think I didn´t quite understand the way you can add the code (Yes, I´ve read the instructions :).

I´ve copy/pasted your code inside limit_comments.js (that´s inside limit_comments folder, with the .module file).
Then I added this line at the beggining of the .module file:
drupal_add_js(drupal_get_path('module', 'limit_comments') .'/limit_comments.js');

But it won´t work. The limit exists, the module works, but it seems that it just won´t call the js file...
How should I do this?
Thanks!!
Rosamunda

Drave Robber’s picture

It needs to be added in some function that is sure to be called before the output. The most common place to add js and CSS is hook_init():

function yourmodule_init() {
  drupal_add_js(drupal_get_path('module', 'limit_comments') .'/limit_comments.js');
}

(yourmodule here is to be replaced by your module's name)

If you want to add it only to node pages that can actually be commented on, then you can add a condition:

function yourmodule_init() {
  $where = menu_get_object();
  if ($where->comment == 2) {  // Numeric value of COMMENT_NODE_READ_WRITE
    drupal_add_js(drupal_get_path('module', 'limit_comments') .'/limit_comments.js');
  }
}
abs13’s picture

Thank you very much for this mini module, it works fine! I am using it to create something like a shoutbox using Drupals build-in comments. The only problem i have is that when form validation fails I get redirected to "comment/reply/" but I want Drupal to stay on the current page and show the error message there. Any suggestions?

shenzhuxi’s picture

check http://drupal.org/node/572398
I added comment limit to maxlength module.

Cristobal Wetzig’s picture

I feel this problem can be solved much simpler (drupal 6 example). Also it will override comment module functions witch among other things sets cookies, and other magic.

IF you just wan to limit the characters for a comment you can do :

function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {

 if ($form_id == 'comment_form') {
	$form['comment_filter']['comment'] = array(
    '#type' => 'textarea',
    '#title' => t('Comment'),
    '#rows' => 15,
		'#maxlength' => 500,
    '#default_value' => $default,
    '#required' => TRUE,
  );
 }
}
 

The validation is now taken care for you by drupalmagic (form api).
All you need to do is to invoke the #maxlength element, so even passing the array is unnecessary.

marcvangend’s picture

You are correct, using #maxlength is a better way to do that. However your code could override changes that may have been made by other hook_form_alter implementations (a changed #title for instance). A better way would be to only add the #maxlength property:

function YOURMODULENAME_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'comment_form') {
    $form['comment_filter']['comment']['#maxlength'] = 500;
  }
}

Another obvious reason why your code is simpler than the original, is that it lacks an admin form to set the limit and an implementation of hook_help. However that's a choice developers can make for themselves.

Cristobal Wetzig’s picture

Good point!

I was to hasty on my reply, I noticed I even left a $default variable in there.
Thank you for sharing.

tebdilikiyafet’s picture

Is there any way to do this for a specific node type? Can we customize your code for a specific node type?
I tried but I could not. I think $nodetype variable is not accesible here.

Sepero’s picture

I created the folder /sites/all/modules/limit_comments
I put the file "limit_comments.module" in there.
I put the code listed on this page into the file.
I removed "?>" from the end of the file.

I cannot see this module in the modules list.

I'm using D6.
Help?

marcvangend’s picture

You also need a limit_comments.info file. See the module developers guide to see what it should contain.

Sepero’s picture

Okay, I made the limit_comments.info file with the following and now I see it in the modules list. thx
limit_comments.info

; $Id$
name = "Limit Comments"
description = "Limit Comments"
core = 6.x
package = Other
Anonymous’s picture

(Drupal 6.x)

?>  
    $form['comment_filter']['comment'] = array(
    '#type' => 'textarea',
    '#title' => t('Comment (Max. number of characters: 139)'),
    '#rows' => 15,
    '#default_value' => $default,
    '#maxlength' => 150, //added to limit the number of characters
    '#required' => TRUE,
  );

..on file /modules/comment/comment.module
Obviously this is an approximate solution, but very quick and easy to apply. The problem is that when you have to update your core modules you have to add this line again.