Skip to content

Instantly share code, notes, and snippets.

@flexseth
Forked from hiranthi/zipcode-2.php
Created May 9, 2019 17:33
Show Gist options
  • Save flexseth/08e9e6d939096832542b48ab775aaade to your computer and use it in GitHub Desktop.
Save flexseth/08e9e6d939096832542b48ab775aaade 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment