I would like to validate the file type of a file uploaded using Form CRED. Only PDFs should be allowed.
For images I would like to validate only images that are larger than 85 KB and smaller than 1024 KB
Post Form:
Name: Job-Form einfuegen
slug: job-form-einfuegen
Form ID: 375
Custom Field for PDF (File):
Name: Testpdf;
Slug: testpdf
Custom Field for image (Image):
Name: Testimage
Slug: testimage
I´m using the option "Use the WordPress Media Library manager for image, video, audio, or file fields", witn filter hook "cred_form_ajax_upload_validate":
<?php
/**
* New custom code snippet (replace this with snippet description).
*/
toolset_snippet_security_check() or die( 'Direct access is not allowed' );
// Put the code of your snippet below this comment.
//Limit the upload file type PDF and size for the custom field.
add_filter('cred_form_ajax_upload_validate','wpbd_member_form_validation',10,2);
function wpbd_member_form_validation ($error_fields, $form_data)
{
//field data are field values and errors
list($fields,$errors)=$error_fields;
//validate if specific form
if ($form_data['id'] == 375)
{
//check image size
if ($fields['wpcf-testimage']['field_data']['size'] > 85 * 1024)
{
//set error message
$errors['wpcf-testimage'] = 'Wrong image size!';
}
if ( ($fields['wpcf-testpdf']['field_data']['size'] > 55 * 1024) || ($fields['wpcf-testpdf']['field_data']['type'] != 'application/pdf') )
{
//set error message
$errors['wpcf-testpdf'] = 'Wrong size Or document type! only pdf allowed!';
}
}
//return result
return array($fields,$errors);
}
I did some tests in the "testpdf field" with Image files and Word files, but the Form did not block the sending of the files.
Where am I wrong? can you help me please?.
Luo is on vacation. This is Minesh here and I'll take care of this ticket. Hope this is OK.
Instead of "cred_form_ajax_upload_validate" hook what if you try to use the "cred_form_validate" hook.
For example:
add_filter('cred_form_validate','func_cred_filetype_validation',10,2);
function func_cred_filetype_validation($error_fields, $form_data) {
//field data are field values and errors
list($fields,$errors)=$error_fields;
//validate if specific form
if ( $form_data['id']==375 ) {
//check image size
if ($fields['wpcf-testimage']['field_data']['size'] > 85 * 1024) {
//set error message
$errors['wpcf-testimage'] = 'Wrong image size!';
}
if ( ($fields['wpcf-testpdf']['field_data']['size'] > (55 * 1024) ) || ($fields['wpcf-testpdf']['field_data']['type'] != 'application/pdf') ) {
//set error message
$errors['wpcf-testpdf'] = 'Wrong size Or document type! only pdf allowed!';
}
}
//return result
return array($fields,$errors);
}