Skip to content

Instantly share code, notes, and snippets.

@hiranthi
Last active January 17, 2020 00:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hiranthi/b23884c144c5000db535b19a38c0a2f6 to your computer and use it in GitHub Desktop.
Save hiranthi/b23884c144c5000db535b19a38c0a2f6 to your computer and use it in GitHub Desktop.
Zipcode validation for Gravity Forms (5 digits, 2 approaches).
<?php
# just add the needed form IDs to the array
$forms = array( '6', '7' );
# 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 . '.5' );
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
<?php
# the filter, change 7 to the actual form ID
add_filter( 'gform_field_validation_7', '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 . '.5' );
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
<?php
# each form ( + field ID) its own 'add_filter'
add_filter( 'gform_field_validation_6_15', 'custom_zip_validation', 10, 4 );
add_filter( 'gform_field_validation_7_15', 'custom_zip_validation', 10, 4 );
# the function
function custom_zip_validation( $result, $value, $form, $field )
{
if ( $result['is_valid'] )
{
$zip_value = rgar( $value, $field->id . '.5' );
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
@hiranthi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment