Erich H.
Erich H.

Reputation: 467

Validate file extensions and file size on Drupal 7 file field using the form API

I am using Drupal 7 and have a custom module that creates a form that has a file upload field:

$form['resume_file'] = array(
  '#type' => 'file',
  '#title' => t('Resume Upload'),      
);

I need to make sure the file extensions are one of the following: doc, docx, pdf, txt and rtf and that the file size is no larger than 2MB

I am not finding a clear way in the docs to accomplish this. I saw one place that said use this:

$form['resume_file'] = array(
  '#type' => 'file',
  '#title' => t('Resume Upload'),
  '#upload_validators'  => array("file_validate_extensions" => array("doc docx pdf txt rtf")),
);

but that didn't do anything as far as blocking the wrong filetype and giving an error message. Do I need to do something else like have something extra in my hook_form_validate() function?

I also saw this:

$form['resume_file'] = array(
  '#type' => 'file',
  '#title' => t('Resume Upload'),
);

$form['resume_file']['#upload_validators']['file_validate_extensions'][0] = 'doc docx pdf txt rtf'; 

Which also did not do anything. How do I validate for file size and extensions?

Upvotes: 1

Views: 7173

Answers (3)

Mehul Jethloja
Mehul Jethloja

Reputation: 637

The file upload control in form api in druapl 7 with extension and size validation

'resume'=>array(
  '#type'   => "managed_file",
  '#title'  => t("Upload Resume in Word Format"),
  '#descripion' => t("Only doc or docx format Files are allowed."),
  '#upload_location'    => "public://resume/",
  "#upload_validators"  => array("file_validate_extensions" => array("doc docx")),
  '#required'=>TRUE,

),

Upvotes: 3

The #upload_validators is part of the non-standard form element properties for a managed file form element.

$element = array(
  '#type' => 'managed_file',
  '#title' => t('Resume Upload'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);

For more information on the managed file element type see the Drupal Form API reference

Upvotes: 1

Sumoanand
Sumoanand

Reputation: 8929

It should work actually. We just need to mention file_validate_extensions & file_validate_size under upload_validators.

Example:

'#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),

Upvotes: 4

Related Questions