Drupal – Add additional validation on Drupal form

We can use a custom module to add additional validation on any Drupal form without affecting the build-in validation. Add the following 2 functions in your .module file.

function <module>_form_alter(&$form, &$form_state, $form_id) {  
  if ($form_id == '<form-id>') {
    // Add the extra validation
    array_unshift($form['#validate'], 'addtional_validate');
  }
}

function addtional_validate($form, $form_state) {
  // Check a user reference field called field_user_reference
  if ($form_state['values']['uid'] == $form_state['values']['field_user_reference']['und'][0]['uid']) {
    form_set_error('field_user_reference', t('You could not reference yourself.'));
  }

  // You can add more validation by checking the $form_state['values']
}

 

Done =)

Reference: fused – Add an additional validation function to an existing Drupal form

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.