Add custom validator to a filefield

Last modified: August 11, 2009 - 16:21

Sometimes, it might be necessary to add validation code to a filefield field. For example, in case you allow uploading a very specific file type, you might want to check that the user is uploading a valid file and not just one with the correct file extension. In order to do so, a validator must be added to filefield.

This can be done by changing (altering) the code of the form, which includes the filefield. Therefore, you have to implement hook_form_alter() in a custom module:

function example_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'ID_OF_YOUR_FORM')
    return;

  $form['FIELDNAME'][0]['#upload_validators']['example_FUNCTIONNAME'] = array();

  return $form;
}

Now, the validator function must be provided, too.

function example_FUNCTIONNAME($field) {
  // variable for error messages
  $errors = array();

  // do some processing on the field
  $filepath = $field->filepath;

  ...

  // in case of error, add error message
  $errors[] = t('Validation failed, because...');

  return $errors;
}

It is important that your module gets processed after the modules filefield and CCK. If your module is processed before, the filefield code won't be present in the $form variable in hook_form_alter(...) and it is impossible to add a validation handler. The processing order of modules is controlled by their weight stored in the {system} table. The example module must have a larger value than content (CCK) and filefield. See http://drupal.org/node/110238 for details on how to adjust the weight value.

hi there, i need to validate

hatsch - December 3, 2009 - 19:32

hi there,
i need to validate a file field. this is my first custom module, so maybe i just miss something very trivial...
actually there is no real validation yet but i just return $errors[] = t('Validation Error'); so in my understanding there should be an error everytime i save the node
unfortunately the code doesn't seem to work.

function upload_duration_form_alter(&$form, $form_state, $form_id) {
//if ($form_id != 'page_node_form')
//  return;
$form['field_videoclip'][0]['#upload_validators']['upload_duration_ckeckduration'] = array();
return $form;

function upload_duration_checkduration($field) {
$errors = array();
$errors[] = t('Validation Error');
return $errors;

thank you for any suggestions?

edit:
i set the module weight to 99 with the util module.

solved

hatsch - December 5, 2009 - 14:14

i don't know exactly what was wrong with my code, but the additional validation is now working. thanks for your code snipplets :)

 
 

Drupal is a registered trademark of Dries Buytaert.