Skip Navigation

[Resolved] Validate the image field (Repeating) in the Post Form in Toolset

This thread is resolved. Here is a description of the problem and solution.

Problem:
The user would like to validate an image field(repeatable) in a Toolset form for the image type, size, dimensions, and number of images

Solution:
This will require custom code. Check this example code:

add_action('cred_form_validate', 'my_image_validation_func',10,2);
function my_image_validation_func($error_fields, $form_data) {
    // all the valid file types
    $file_types = array('image/jpeg','image/png','image/jpg');
    $max_size = 5 * 1024 * 1024;
    $forms = array( 1806 );
 
    // Field data are field values and errors
    list($fields,$errors)=$error_fields;
 
    if (in_array($form_data['id'], $forms ) && (isset($_FILES['wpcf-book-images']['type']))) {
        // 1. Minimum number of photos is '3'.
        if ( count( $_FILES['wpcf-book-images']['name'] ) < 3 ) {
            $errors['wpcf-book-images'] = 'Add at least 3 images';
            return array( $fields, $errors );
        }
 
        // 2. Dimensions of the photo should be at least 350 (height) x 350 (width).
        foreach ( $_FILES['wpcf-book-images']['tmp_name'] as $tmp_image ) {
            $sizes = getimagesize( $tmp_image );
            if ( $sizes[0] < 350 || $sizes[1] < 350 ) {
                $errors['wpcf-book-images'] = 'An image is too small. Images should be at least 350x350';
                return array( $fields, $errors );
            }
        }
 
        // 3. The file types should be JPG, PNG and JPEG.
        foreach ( $_FILES['wpcf-book-images']['type'] as $type ) {
            if ( !in_array( $type, $file_types ) ) {
                $errors['wpcf-book-images'] = 'Image file type is not supported: ' . $type;
                return array( $fields, $errors );
            }
        }
 
        // 4. Maximum file size should be 5MB.
        foreach ( $_FILES['wpcf-book-images']['size'] as $size ) {
            if ( $size >= $max_size ) {
                $errors['wpcf-book-images'] = 'An Image is too big. Images should less than 5MB';
                return array( $fields, $errors );
            }
        }
    }
 
    //return result
    return array($fields,$errors);
}

Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

This support ticket is created 3 years, 3 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 9:00 – 13:00 - - 9:00 – 13:00
14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 - - 14:00 – 18:00

Supporter timezone: Africa/Casablanca (GMT+00:00)

This topic contains 19 replies, has 3 voices.

Last updated by pramodk-2 2 years, 12 months ago.

Assisted by: Jamal.

Author
Posts
#1886593

Hi Team,

In my requirement, there is a image field (Repeating field) in the post form with the below conditions to validate.

1. Minimum number of photos is ‘3’.
2. Dimensions of the photo should be at least 350 (height) x 350 (width).
3. The file types should be JPG, PNG and JPEG.
4. Maximum file size should be 5MB.

Referred to the below link:
https://toolset.com/forums/topic/cred-validation-of-filetype-and-size/

Is there any code to refer where all the above conditions can be validated?

My website which is in development phase: hidden link

Thanks.
Pramod.

#1889639

Jamal
Supporter

Languages: English (English ) French (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Hello and thank you for contacting the Toolset support. My apologies for the late reply, but I had to run some tests before getting back to you.

Keep in mind, that a repeatable image field, will be sent as an array. So, if we have a field 'Book Images', its actual meta key that would be used will be named 'wpcf-book-images' (Notice how Toolset uses this prefix 'wpcf-'). And on the server, if we try to log its content with:

error_log($_FILES['wpcf-book-images']);

We'll get an array such as:

Array
(
    [name] => Array
        (
            [0] => 80wYSpqSxX8.jpg
        )

    [type] => Array
        (
            [0] => image/jpeg
        )

    [tmp_name] => Array
        (
            [0] => C:\xampp\tmp\php4498.tmp
        )

    [error] => Array
        (
            [0] => 0
        )

    [size] => Array
        (
            [0] => 66775
        )

)

So, the custom validation code needs to check each image from the array.

Check this sample code:

add_action('cred_form_validate', 'my_image_validation_func',10,2);
function my_image_validation_func($error_fields, $form_data) {
	// all the valid file types
	$file_types = array('image/jpeg','image/png','image/jpg');
	$max_size = 5 * 1024 * 1024;
	$forms = array( 1806 );

	// Field data are field values and errors
	list($fields,$errors)=$error_fields;

	if (in_array($form_data['id'], $forms ) && (isset($_FILES['wpcf-book-images']['type']))) {
		// 1. Minimum number of photos is '3'.
		if ( count( $_FILES['wpcf-book-images']['name'] ) < 3 ) {
			$errors['wpcf-book-images'] = 'Add at least 3 images';
			return array( $fields, $errors );
		}

		// 2. Dimensions of the photo should be at least 350 (height) x 350 (width).
		foreach ( $_FILES['wpcf-book-images']['name'] as $tmp_image ) {
			$sizes = getimagesize( $tmp_image );
			if ( $sizes[0] < 350 || $sizes[1] < 350 ) {
				$errors['wpcf-book-images'] = 'An image is too small. Images should be at least 350x350';
				return array( $fields, $errors );
			}
		}

		// 3. The file types should be JPG, PNG and JPEG.
		foreach ( $_FILES['wpcf-book-images']['type'] as $type ) {
			if ( !in_array( $file_type_uploaded, $types ) ) {
				$errors['wpcf-book-images'] = 'Image file type is not supported';
				return array( $fields, $errors );
			}
		}

		// 4. Maximum file size should be 5MB.
		foreach ( $_FILES['wpcf-book-images']['size'] as $size ) {
			if ( $size >= $max_size ) {
				$errors['wpcf-book-images'] = 'An Image is too big. Images should less than 5MB';
				return array( $fields, $errors );
			}
		}
	}

	//return result
	return array($fields,$errors);
}

Notice how we use "foreach" to loop through the array and check each image.

I hope this gives you an idea of how to implement the validation. Let me know if you still have any questions.

#1889707
Image validation.png

Hi Jamal,

Many thanks for your code.

However, I have faced the below problems after using the code.

1. Always throwing an error even after the images attached are correct.
Example:
(i) Even after file is 350 x 350, it is still showing the error that the it is too small.
(ii) Even after giving the correct file size, it is still saying the file type is incorrect.

2. Also, when there is an error in the image field, the image option to include is auto incremented.
Please check the image attached for more details where I have not selected those to add the images but auto incremented.

Since my website is not advertised to anyone to start using it, just created a page for you with only this field to check what I am trying to say.
hidden link

Let me know in case you in case you need credentials to check the back end.

Thanks.

#1892673

Jamal
Supporter

Languages: English (English ) French (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Sorry,

I made an error on lines 19 and 29. The code should be:

add_action('cred_form_validate', 'my_image_validation_func',10,2);
function my_image_validation_func($error_fields, $form_data) {
    // all the valid file types
	$file_types = array('image/jpeg','image/png','image/jpg');
	$max_size = 5 * 1024 * 1024;
	$forms = array( 1806 );

	// Field data are field values and errors
	list($fields,$errors)=$error_fields;

	if (in_array($form_data['id'], $forms ) && (isset($_FILES['wpcf-book-images']['type']))) {
		// 1. Minimum number of photos is '3'.
		if ( count( $_FILES['wpcf-book-images']['name'] ) < 3 ) {
			$errors['wpcf-book-images'] = 'Add at least 3 images';
			return array( $fields, $errors );
		}

		// 2. Dimensions of the photo should be at least 350 (height) x 350 (width).
		foreach ( $_FILES['wpcf-book-images']['tmp_name'] as $tmp_image ) {
			$sizes = getimagesize( $tmp_image );
			if ( $sizes[0] < 350 || $sizes[1] < 350 ) {
				$errors['wpcf-book-images'] = 'An image is too small. Images should be at least 350x350';
				return array( $fields, $errors );
			}
		}

		// 3. The file types should be JPG, PNG and JPEG.
		foreach ( $_FILES['wpcf-book-images']['type'] as $type ) {
			if ( !in_array( $type, $file_types ) ) {
				$errors['wpcf-book-images'] = 'Image file type is not supported: ' . $type;
				return array( $fields, $errors );
			}
		}

		// 4. Maximum file size should be 5MB.
		foreach ( $_FILES['wpcf-book-images']['size'] as $size ) {
			if ( $size >= $max_size ) {
				$errors['wpcf-book-images'] = 'An Image is too big. Images should less than 5MB';
				return array( $fields, $errors );
			}
		}
	}

	//return result
	return array($fields,$errors);
}

While testing this code, the issue of additional file fields was not reproduced.
Can you test this more from your end and if it still presents any issues, please provide an example that will help me reproduce the issue.

#1892957
Repeated image field - Issue two V1.0.png
Repeated image field - Issue one V1.0.png
Repeated image field - Issue three V1.0.png

Hi Jamal,

Thanks for replying back to me.

Created a test page (hidden link) with the details needed and performed testing.

1. I am - This is a mandatory field.
2. Amenities - Added a code snippet with the help of support team to validate at least one checkbox is selected.
3. Property Photos - Added a code snippet provided by you.

Issue One:

Step 1:
1. Code provided by you is deactivated and tested (Property Photos).
(i) Selected 'I am' with some drop down.
(ii) Added an image in 'Property Photos'.
(iii) Clicked 'Submit' button.

Image field is auto incremented. Please find attached the image with 'Repeated image field - Issue one V1.0' name for the same.

Step 2:
2. Code provided by you is activated but the code snippet added for checkbox 'Amenities' is deactivated and tested.
(i) Selected 'I am' with some drop down.
(ii) Added an image in 'Property Photos'.
(iii) Clicked 'Submit' button.

Image field is auto incremented. Please find attached the image with 'Repeated image field - Issue two V1.0' name for the same.

After performing steps 1 & 2, I understand that the image file is auto incremented whenever there is an error thrown from the code snippets (Either from checkbox code snippet provided below OR image code snippet provided by you or BOTH).

Below is the code snippet added for the checkbox field mandatory:

add_filter( 'cred_form_validate', 'tssnippet_at_least_one_checkbox_validation', 10, 2 );
function tssnippet_at_least_one_checkbox_validation( $field_data, $form_data ) {
  
    $target_forms = array( 470 );
    $target_field_slug_1 = 'amenities';
  
    if ( ! in_array( $form_data['id'], $target_forms ) ) {
        return $field_data;
    }
  
    // $field_data contains fields values and errors
    list( $fields, $errors ) = $field_data;
  
    if ( ! isset( $fields[ 'wpcf-' . $target_field_slug_1 ]['value'][0] ) ) {
        $errors[ $target_field_slug_1 ] = 'At least one checkbox is required';
    }
  
    return array( $fields, $errors );
}

Issue Two:

Code provided by you is deactivated and tested (Property Photos).I have tried to add different formats like doc, excel, MP4, PDF etc ., it is saying 'You can only add an image file' seems the file type functionality is a default functionality and do not need any additonal code to validate again. Please let me know whether my understanding on this is correct.

Please go through my findings and let me know.

Also, let me know in case you need my backend access to check it.

Thanks.

#1893817

Jamal
Supporter

Languages: English (English ) French (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Thank you for your feedback. I was able to reproduce the issue on a clean install, whether the validation fails for the image field or another field. So, I am escalating this to our 2nd Tier for another analysis.

Regarding the other file types(PDF, doc, etc), it won't work, because that's an image field, and will only accept images. If you need to upload such files, you need to use a File field instead of an image field.

#1893837

Hi Jamal,

Thanks for your response.

Please find my inline comments below:

Thank you for your feedback. I was able to reproduce the issue on a clean install, whether the validation fails for the image field or another field. So, I am escalating this to our 2nd Tier for another analysis.
Pramod - Thanks, will wait for the response.

Regarding the other file types(PDF, doc, etc), it won't work, because that's an image field, and will only accept images. If you need to upload such files, you need to use a File field instead of an image field.
Pramod - Apologies in case my explanation caused a confusion. I'm trying to say that the below code provided by you is not needed to check the file type since it is anyway a built in functionality that it allows image file type only.

// 3. The file types should be JPG, PNG and JPEG.
        foreach ( $_FILES['wpcf-book-images']['type'] as $type ) {
            if ( !in_array( $type, $file_types ) ) {
                $errors['wpcf-book-images'] = 'Image file type is not supported: ' . $type;
                return array( $fields, $errors );
            }
        }

Thanks.

#1894647

Jamal
Supporter

Languages: English (English ) French (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Hi Pramod,

If you will accept all types of images, you can omit that part of the code. But if you want to enable only the following types, you need to keep that part of the code:
.jpg
.jpeg
.png
For example, (.gif) images are supported by WordPress, but this code will not accept them.

Regarding the issue of the additional file input, it is now escalated to the developers. I'll get back to you as soon as we have any news about it.

#1894709

Hi Jamal,

Thanks for the response.

Will wait until there is a response from the developers.

Thanks.

#1900311

Hi Jamal,

Any updates?

Thanks.

#1901465

Jamal
Supporter

Languages: English (English ) French (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Hello Pramod,

Unfortunately, the developers did not get this issue yet. We don't have an ETA for it. But, I'll keep you informed as soon as we have any news.

In the meantime, you may consider using the native Media Manager in your form. Check this screenshot hidden link
Note that it will be available only to logged-in users.

Best regards.

#1901467

Hi Jamal,

As per my requirement, we cannot use media manager to upload the images.

It is been a week already and would appreciate at least an update with solution within next week and not more than that as I would need to meet my deadline. Hope you understand and apologies for chasing.

Thanks.

#1902057

Jamal
Supporter

Languages: English (English ) French (Français )

Timezone: Africa/Casablanca (GMT+00:00)

Hello Pramod,

I do understand that you need to meet your deadlines, and I would understand if you feel frustrated because of the time that this can take. But we cannot guarantee when this will be solved. And I am afraid it won't be fixed next week. Because the current dev sprint is focused on other issues. I also cannot guarantee if this issue would be added to the next sprint.

Our sincere apologies for any inconvenience this may create for you.

#1902063

Hi Jamal,

All that is fine, but would need at least some approximate time by when we would expect the reply.

Almost everything about my website is almost done and waiting for it.

Thanks.

#1902303

Nigel
Supporter

Languages: English (English ) Spanish (Español )

Timezone: Europe/London (GMT+01:00)

Hi there

We are in the final stages of the current development cycle, close to freezing code and entering final testing, which is likely to take a couple of weeks (including this one).

The ticket for this issue is included in the board for the next cycle that will begin immediately thereafter. Each cycle typically takes a couple of months, but I've added a note to the internal ticket to see if a patch can be made available to you when it is fixed, rather than waiting for the cycle to complete and the full plugin update become available. As soon as something is available from the developers, we'll get it to you.

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.