Gravity Forms Image Aspect Ratio Validation
Despite giving very specific instructions, sometimes users don’t follow them. By default, Gravity Forms does not offer image aspect ratio validation on a file input field, so I had my n8n WordPress code chat agent generate this. I have not tried using the code, and this was for a specific form, so it would need to be modified and tested before use.
1/**
2 * Validates the image aspect ratio for form ID 1, field ID 9.
3 *
4 * Update the form ID and field ID in the filter hook and input name references
5 * if these change in Gravity Forms.
6 */
7
8add_filter( 'gform_field_validation_1_9', function ( $result, $value, $form, $field ) {
9
10 // Helper function for aspect ratio validation
11 function is_aspect_ratio_close( $width, $height, $target_ratio = 4 / 3, $tolerance = 0.01 ) {
12 if ( $height === 0 ) {
13 return false; // Prevent division by zero
14 }
15 $current_ratio = $width / $height;
16 return ( abs( $current_ratio - $target_ratio ) <= $tolerance );
17 }
18
19 // Get uploaded file tmp_name safely using $_FILES currently (Gravity Forms does not expose it directly)
20 $field_id = (string) $field->id;
21 if ( empty( $_FILES["input_{$field_id}"]['tmp_name'] ) ) {
22 return $result; // No file uploaded, skip
23 }
24
25 $file_path = $_FILES["input_{$field_id}"]['tmp_name'];
26 $image_info = @getimagesize( $file_path ); // @ to suppress warnings on invalid images
27
28 if ( false === $image_info ) {
29 // Invalid image file
30 $result['is_valid'] = false;
31 $result['message'] = __( "The uploaded file is not a valid image.", 'ufl-main-uni-child' );
32 return $result;
33 }
34
35 list( $width, $height ) = $image_info;
36
37 if ( ! is_aspect_ratio_close( $width, $height ) ) {
38 $result['is_valid'] = false;
39 $result['message'] = __( "Invalid aspect ratio. Please upload a 4:3 image (e.g., 1024x768).", 'ufl-main-uni-child' );
40 return $result;
41 }
42
43 return $result;
44
45}, 10, 4 );