2

For a file field, it’s required to enter file extensions in "Allowed file extensions".

Is there a way to allow any file extension? Or a way to switch from a whitelist to a blacklist?

What I found

1 Answer 1

2

Implement a hook alter on the node form or the field level and in it change the validator to your custom function:

/**
 * alter form field element:.
 * 
 * Implements hook_FORM_alter
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
    $upload_validators = array(
        'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
    );
    $form['your_file_field_element']['#upload_validators'] = $upload_validators;

}

Alternatively you can change the behavior of the field on any node, or entity by altering the widget form:

function mymodule_field_widget_form_alter(&$element, &$form_state, $context) {  
   if ( "condition to check if it's your field" == TRUE) {
     $upload_validators = array(
            'my_module_file_validate_extensions_blacklist' => ['jpg jpeg gif png mp4']
        );
        $element['#upload_validators'] = $upload_validators;
  }
}

Then write you own function to do what you want:

function my_module_file_validate_extensions_blacklist(stdClass $file, $extensions) {
  $errors = array();
  $regex = '/\\.(' . preg_replace('/ +/', '|', preg_quote($extensions)) . ')$/i';
  if (preg_match($regex, $file->filename)) {
    $errors[] = t('files with the following extensions are not allowed: %files-allowed.', array(
      '%files-allowed' => $extensions,
    ));
  }
  return $errors
}

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.