26

I need to add custom validation to a form, lets says add article form.

I was expecting something like hook_FORM_ID_validate() to handle this, but cannot find anything relavant in the API documentation.

What is the way to add custom validation to a form?

52

You can add any number of validation functions to any form in hook_form_FORM_ID_alter() like so:

function mymodule_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  // There will already be some validate handlers added so you need to add to the
  // array rather than overwrite it.
  $form['#validate'][] = 'mymodule_article_form_validate';

  // As mentioned above you can add as many as you want
  $form['#validate'][] = 'mymodule_article_form_validate_2';
}

function mymodule_article_form_validate($form, &$form_state) {
  // Random example, if the title is 'test' throw an error
  if ($form_state['values']['title'] == 'test') {
    form_set_error('title', 'Title cannot be "test"');
  }
}
  • Suppose i've added custom form validation to a form which have already 2 validation function. Then which is get first preference in drupal 7? – Guru Sep 7 '15 at 12:25
  • Which ever is first in the array @Guru – Clive Sep 7 '15 at 12:26
  • If the form is user_registration_form, then it always keeps "[#validate] => Array ( [0] => user_account_form_validate [1] => user_validate_picture )". Suppose i'm going to add custom validation. Then it should be like this "[#validate] => Array ( [0] => user_account_form_validate [1] => user_validate_picture [2] => user_register_validate )". But i want to run "user_register_validate" function at first. – Guru Sep 7 '15 at 12:36
  • For other fields, you got to use: if ($form_state['values']['field_custom']['und'][0]['value'] == 'Error') { //throw error } – Chris Happy Apr 27 '18 at 22:36
  • how to set validation for size, extension in this manner? And one more question, if there is ajax functionality like"upload" and "remove" how we handle validation for this? – steniya May 17 at 10:25
5

You should use hook_form_alter and add your function to the #validate property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.