Checking file types and sizes with #upload_validatorsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

Following our exploration of custom validation logic with validateForm(), this lesson shifts focus to file handling using #upload_validators in Drupal’s Form API. Proper validation of file types and sizes is essential for maintaining application security and performance, ensuring uploads meet predetermined criteria.

Introduction to #upload_validators

The #upload_validators property specifies validation constraints for file uploads, targeting file type and size. By enforcing these guidelines, you mitigate risks associated with unwanted file types and excessively large uploads, safeguarding your application from security vulnerabilities.

Benefits of File Type and Size Validation

Using the #upload_validators offers several advantages:

  • Security: Limits exposure by allowing only designated file types, reducing the risk of executable or harmful files.
  • Performance: Ensures file uploads remain manageable in size, preventing resource exhaustion or application slowdown.
  • Data Integrity: Ensures files conform to application-specific requirements, aligning with business and user expectations.

Implementing #upload_validators

Consider an application where users can upload profile pictures, with restrictions on file type and size:


function profile_form($form, &$form_state) {
    $form['profile_picture'] = [
        '#type' => 'managed_file',
        '#title' => t('Profile Picture'),
        '#upload_location' => 'public://profile_pictures/',
        '#upload_validators' => [
            'file_validate_extensions' => ['png jpg jpeg'],
            'file_validate_size' => [1024 * 1024 * 2], // 2 MB limit
        ],
    ];

    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => t('Save Profile'),
    ];

    return $form;
}

        

In this setup, "Profile Picture" accepts files only with png, jpg, or jpeg extensions. Additionally, the file size must not exceed 2 MB, as defined by the file_validate_size validator.

Strategies for Effective File Validation

Consider these strategies to enhance file upload integrity:

  • Comprehensive Extension Checking: Align accepted extensions closely with the intended use of the file (e.g., images, documents).
  • Size Considerations: Balance performance and user needs by setting realistic file size limits.
  • Feedback with Custom Messages: Customize error messages to be user-friendly and instructive, guiding the user on correct file submission.

Advanced File Handling

For more control over files, consider dynamic validation based on other form inputs or user roles:


function advanced_file_upload_form($form, &$form_state) {
    $user_role = \Drupal::currentUser()->getRoles(); 

    $max_size = in_array('administrator', $user_role) ? 1024 * 1024 * 5 : 1024 * 1024 * 2; // 5MB for admins, 2MB for others

    $form['supporting_documents'] = [
        '#type' => 'managed_file',
        '#title' => t('Supporting Documents'),
        '#upload_validators' => [
            'file_validate_extensions' => ['doc pdf'],
            'file_validate_size' => [$max_size],
        ],
    ];
}

        

Here, file size limits adapt based on user role, allowing administrators to upload larger files while maintaining stricter limits for other users.

Conclusion

The #upload_validators property within Drupal's Form API ensures file uploads are safe and managed effectively. By implementing these validations, you safeguard data consistency, system performance, and security, creating a robust and scalable application environment.

What’s Next?

The next topic in our series explores using hook_form_alter() to modify validation, offering deeper insights into customizing validation in Drupal forms. Stay tuned as we further enhance your Drupal expertise!