Search code examples
drupaldrupal-7

how to limit title length in Drupal?


I would like to provide validation for title length. Right now I get an exception:

PDOException: SQLSTATE[22001]: String data, right truncated: 
1406 Data too long for column 'title' at row 1: 
INSERT INTO {accesslog} (title, path, url, hostname, uid, sid, timer, timestamp) 
VALUES (...) in statistics_exit() (line 90 of 
/opt/bitnami/apps/.../htdocs/modules/statistics/statistics.module).

I tried http://drupal.org/project/maxlength and http://drupal.org/project/maxlength_js, but no luck.


Solution

  • I coded custom validation module

    function custom_validate_form_alter(&$form, &$form_state, $form_id) {
      if ( $form_id =='user_register_form') {
        $form['#validate'][] = '_custom_validate_form_alter_user_register_validate';
       }
       if ( $form_id =='user_profile_form') {
          $form['#validate'][] = '_custom_validate_form_alter_user_profile_validate';
       }
       $types = array("your_content_type_node_form");
       if(in_array($form_id, $types)){
         $form['#validate'][] = '_custom_validate_form_alter_title_node_form_validate';
        }
        return $form;
     }
    
     function _custom_validate_form_alter_user_register_validate($form, &$form_state) {
       if (strlen($form_state['values']['name'])>30){
         form_set_error('name', 'Username must be less than 30 characters. Please correct username');
        }
       }
    function _custom_validate_form_alter_user_profile_validate($form, &$form_state) {
      if(!empty($form_state['values']['pass']) && strlen($form_state['values']['pass'])>30){
        form_set_error('pass', 'Password must be less than 30 characters. Please correct password');
      }
      if(!empty($form_state['values']['pass']) && strlen($form_state['values']['pass'])<6){
        form_set_error('pass', 'Password must be at least 6 characters long. Please correct password');
      }
    }
    function _custom_validate_form_alter_title_node_form_validate($form, &$form_state) {
      if (strlen($form_state['values']['title'])>200){
        form_set_error('title', 'Title must be less than 200 characters. Please correct title');
      }
    }