Drupal - How to actually set a maxlength for textarea field in contact form

The Form API does not allow to set a maxlength on textarea field types [while plain HTML does]

That's not strictly true....HTML5 introduced a maxlength property for textareas, previous versions do not have it (see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea).

The default templates that come with Drupal 7 all use XHTML, so the lack of explicit support for HTML5 makes perfect sense.

As long as your doctype is HTML5, this will probably work:

$form['element'] = array(
  '#type' => 'textarea',
  '#attributes' => array('maxlength' => 200),
);

You can use Maxlength module like this, put both #maxlength and #maxlength_js properties on the elements you want to control.

$form['comments'] = array(
  '#type' => 'textarea',
  '#title' => t('Comments'),
  '#maxlength_js' => TRUE,
  '#maxlength' => 1000,
);

Firstly off I defined a setting form, then made a hook form alter:

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

  if ($form_id == 'contact_site_form') {
    $maximum_limit = (int) variable_get('contact_form_maxlength', 500);
    if($maximum_limit && is_numeric($maximum_limit)) {
    $form['message']['#title'] = $form['message']['#title'] . t(' (maximum @max characters)', array( '@max' => $maximum_limit));
    $form['message']['#maxlength'] = $maximum_limit ;
    }
  }
}

This seems to be working fine.

Tags:

Forms

Emails