I was wondering if there's a way to validate a file's size with the form validation class in CodeIgniter 2.0. I have a form that contains a file input and I want to do something like this:
$this->form_validation->set_rule('file', 'File',
'file_type[image/jpeg|image/gif|image/png]|file_max_size[500]');
I thought about extending the validation class to combine it with the upload class and validate based on the upload data, but that might be time consuming.
Does anyone know of any extensions for the form validation class that would do something like this?
I had the same problem. I built a contact form that allows the user to upload an avatar and edit other info at the same time. Form validation errors are shown separately for each field. I could not afford a different display scheme for the file input and the other ones - I have a standard method that takes care of displaying errors.
I used a controller defined property and a callback validation function to merge any upload error with the form validation ones.
Here is an extract of my code:
# controller property
private $custom_errors = array();
# form action controller method
public function contact_save()
{
# file upload for contact avatar
$this->load->library('upload', array(
'allowed_types'=>'gif|jpg|jpeg|png',
'max_size'=>'512'
));
if(isset($_FILES['avatar']['size']) && $_FILES['avatar']['size']>0)
{
if($this->upload->do_upload('avatar'))
{
# avatar saving code here
# ...
}
else
{
# store any upload error for later retrieval
$this->custom_errors['avatar'] = $this->upload->display_errors('', '');
}
}
$this->form_validation->set_rules(array(
array(
'field' => 'avatar',
'label' => 'avatar',
'rules' => 'callback_check_avatar_error'
)
# other validations rules here
);
# usual form validation here
if ($this->form_validation->run() == FALSE)
{
# display form with errors
}
else
{
# update and confirm
}
}
# the callback method that does the 'merge'
public function check_avatar_error($str)
{
#unused $str
if(isset($this->custom_errors['avatar']))
{
$this->form_validation->set_message('check_avatar_error', $this->custom_errors['avatar']);
return FALSE;
}
return TRUE;
}
Note: as the file input will not repopulate if there is any error in the other form fields, on upload success, I store and update it before any other validation takes place - so the user does not need to reselect the file. My notification is a bit different if this happens.
The File Upload Class actually has its own set of validation rules you can set like so
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
(taken from CI docs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With