35

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?

2 Answers 2

63

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"');
  }
}
5
  • 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
    Commented Sep 7, 2015 at 12:25
  • Which ever is first in the array @Guru
    – Clive
    Commented Sep 7, 2015 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
    Commented Sep 7, 2015 at 12:36
  • For other fields, you got to use: if ($form_state['values']['field_custom']['und'][0]['value'] == 'Error') { //throw error } Commented Apr 27, 2018 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
    Commented May 17, 2019 at 10:25
6

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 and acknowledge you have read our privacy policy.

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