1

Does anyone know if it's possible to validate the size of an attachment for Sprout Forms file upload? I'd like to limit attachments to a maximum file size.

1

I'm not sure if that's possible since I never used Sproud Forms but you can easily create a custom field type with the additional validation rule.

  1. Create a Plugin you can use Pluginfactory.io for that and install it
  2. Create a new Field
  3. Just extend the basic AssetsFieldType

    class myNewAssetField extends AssetsFieldType{
    
    }
    
  4. Take a look at the default validation rules for BaseElementFieldType

    public function validate($value)
    {
        $errors = array();
    
        if ($this->allowLimit && ($limit = $this->getSettings()->limit) && is_array($value) && count($value) > $limit)
        {
            if ($limit == 1)
            {
                $errors[] = Craft::t('There can’t be more than one selection.');
            }
            else
            {
                $errors[] = Craft::t('There can’t be more than {limit} selections.', array('limit' => $limit));
            }
        }
    
        if ($errors)
        {
            return $errors;
        }
        else
        {
            return true;
        }
    }
    
  5. Copy the function above in your new class and include something like this somewhere

    foreach ($value as $assetId){
        $asset = craft()->assets->getFileById($assetId);
        if($asset->size >= 10){ // insert your size here
            $errors[] = Craft::t('Your file is too large');
        }
    }
    

It took me about 5 minutes to create this new field type to allow the validation of file sizes

If you want to make it look pretty and create a setting to dynamically set the individual max file size for each field you can include the function getSettingsHtml in your new class and change add your new value (for example maxSize) you can then grab the new size with $this->getSettings()->maxSize

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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