Validating Zip for Single Line Fields

My coding abilities are very limited - I apologize if this is an obvious answer.

I have three zip fields on 2 forms that need to allow only 5 numbers.

I took code from here - Zipcode validation for Gravity Forms (5 digits, 2 approaches). · GitHub and try to adapt it to single line fields, however when I add the code, it applies the filter to every single line field on my forms.

How do I get it to just validate the zip on single line fields with the IDs 17, 43, 63 ?

$forms = array( '2', '4' );

# looping through the array to add an 'add_filter' for each
foreach ( $forms as $i => $form )
    add_filter( "gform_field_validation_{$form}", 'custom_zip_validation', 10, 4 );

# the function
function custom_zip_validation( $result, $value, $form, $field )
{
	if ( ( 'address' == $field->type ) && $result['is_valid'] )
	{	
		$zip_value = rgar( $value, $field->id . '17, 43, 63' );

		if ( ! ctype_digit( $zip_value ) || 5 != strlen( $zip_value ) ) 
		{
			$result['is_valid'] = false;
			$result['message'] = 'Please check your Zip Code. It must be 5 digits only.';
		}
	}
	
	return $result;
} // end custom_zip_validation

You can use this simpler function:

function text_zip_validation( $result, $value, $form, $field ) {
	if ( ! ctype_digit( $value ) || 5 != strlen( $value ) )  {
		$result['is_valid'] = false;
		$result['message'] = 'Please check your Zip Code. It must be 5 digits only.';
	}
	return $result;
}

Then add as many add_filter lines as follows:

add_filter( 'gform_field_validation_xx_yy', 'text_zip_validation', 10, 4 );

Where xx is your form id and yy your field id. For example if you want to apply the validation function to field id 17 in a form that has id 2, you would add this line:

add_filter( 'gform_field_validation_2_17', 'text_zip_validation', 10, 4 );

And just duplicate the line and update the form id and field id to validate other fields.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.