0

**I need to take the values populated by users in 7 separate, single-line input fields and order them in a php array or set so that my built code can read them and validate them against a database **

I have built a functioning php code block that allows me to validate the address field values inputted by users through a Gravity Forms contact form to ensure they match a real world address. If the address does not match, they are not allowed to move forward with the form but instead need to input a valid address.

The code structure is here: `

/**
 * Address Verification
 */
add_filter( 'gform_field_validation_8_21', 'custom_address_validation', 10, 4 );
function custom_address_validation( $result, $value, $form, $field ) {
    //address field will pass $value as an array with each of the elements as an item within the array, the key is the field id
    if ( 'address' === $field->type && $field->isRequired ) {
        GFCommon::log_debug( __METHOD__ . '(): Running.' );
        //address failed validation because of a required item not being filled out
        //do custom validation
        $street1   = rgar( $value, $field->id . '.1' );
        $street2   = rgar( $value, $field->id . '.2' );
        $city      = rgar( $value, $field->id . '.3' );
        $state     = rgar( $value, $field->id . '.4' );
        $zip       = rgar( $value, $field->id . '.5' );
        //$country = rgar( $value, $field->id . '.6' );
 
        //check to see if the values you care about are filled out
        $required_inputs = array( '1' => $street1, '3' => $city, '4' => $state, '5' => $zip );

        $empty_input = false;
 
        foreach ( $required_inputs as $input_number => $input_value ) {
            GFCommon::log_debug( __METHOD__ . '(): Is Hidden? ' . $field->get_input_property( $input_number, 'isHidden' ) );
            if ( empty( $input_value ) && ! $field->get_input_property( $input_number, 'isHidden' ) ) {
                $field->set_input_validation_state( $input_number, false ); // Only for Gravity Forms 2.5.10 or higher.
                $empty_input = true;
                GFCommon::log_debug( __METHOD__ . "(): Empty input: {$field->id}.{$input_number}" );
            }
        }
 
        if ( $empty_input ) {
            $result['is_valid'] = false;
            $result['message']  = empty( $field->errorMessage ) ? 'This field is required. Please enter a street, city, state, and zip.' : $field->errorMessage;
            return $result;
        } else {
            $valid_input=true;
            $valid_url = true;
            $key = "";

            // Begin by removing any leading and trailing spaces in each element (e.g., " Houston" or "Lurleen Wallace ") and then reducing any multi-space sequences (e.g., "   ") to a single space (" ")
            $street1 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $street1);
            $street2 = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $street2);
            $city = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $city);
            $state = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $state);
            $zip = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $zip);
            if (str_contains($street1, " ")) {
                $streetnumber = substr($street1,0,strpos($street1, " ", 0));
                $streetname = substr($street1, strpos($street1, " ", 0)+1,iconv_strlen($street1));
            } else {
                GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );
                $result['is_valid'] = false;
                $result['message']  = $field->errorMessage ? 'This is not a valid address. Please enter the full address where you would like to receive gifts, starting with the street number and street name in Address Line 1.' : $field->errorMessage;
                return $result;
            }

            if ( empty( $street2 )) {
                $street2 = "";
            }
            if (strlen($street2) > 0) {
                $street = $street1 . ", " . $street2;
            } else {
                $street = $street1;
            }

            $address = $street . ", " . $city . ", " . $state . " " . $zip;
            $url = "https://" . "maps.google.com/maps/api/geocode/json?key=" . rawurlencode($key) . "&address=" . rawurlencode("{" . $address . "}");
            $resp_json = file_get_contents($url);
            $resp = json_decode($resp_json, true);

            if ($resp['status']!=='OK') {
                GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );
                $result['is_valid'] = false;
                $result['message']  = empty( $field->errorMessage ) ? 'This is not a valid address. Please enter the address where you would like to receive gifts.' : $field->errorMessage;
                return $result;
            } else {
                foreach($resp['results'] as $res) {
                    $respstreetnumbershort = "";
                    $respstreetnumberlong = "";
                    $respstreetnameshort = "";
                    $respstreetnamelong = "";
                    $respstreet2short = "";
                    $respstreet2long = "";
                    $respcityshort = "";
                    $respcitylong = "";
                    $respstateshort = "";
                    $respstatelong = "";
                    $respzipshort = "";
                    $respziplong = "";

                    foreach ($res['address_components'] as $comp) {
                        if (in_array("street_number", $comp['types'])) {
                            $respstreetnumbershort = $comp['short_name'];
                            $respstreetnumberlong = $comp['long_name'];
                        }
                        if (in_array("route", $comp['types'])) {
                            $respstreetnameshort = $comp['short_name'];
                            $respstreetnamelong = $comp['long_name'];
                        }
                        // It turns out that the API doesn't return the address2 value (e.g., apartment number) at all, so the block below has just been commented out
                        //if (in_array("ADDRESS2_NAME_ON_GOOGLE_MAPS_API", $comp['types'])) {
                        //    $respstreet2short = $comp['short_name'];
                        //    $respstreet2long = $comp['long_name'];
                        //}
                        if (in_array("locality", $comp['types'])) {
                            $respcityshort = $comp['short_name'];
                            $respcitylong = $comp['long_name'];
                        }
                        if (in_array("administrative_area_level_1", $comp['types'])) {
                            $respstateshort = $comp['short_name'];
                            $respstatelong = $comp['long_name'];
                        }
                        if (in_array("postal_code", $comp['types'])) {
                            $respzipshort = $comp['short_name'];
                            $respziplong = $comp['long_name'];
                        }
                    }
                    
                    
                    if (($street1 !== $respstreetnumbershort . " " . $respstreetnameshort) and ($street1 !== $respstreetnumbershort . " " . $respstreetnamelong) and ($street1 !== $respstreetnumberlong . " " . $respstreetnameshort) and ($street1 !== $respstreetnumberlong . " " . $respstreetnamelong)) {
                    //    $valid_input = false;
                    //}
                    //Note: The Google API doesn't even return a value corresponding to the unit/apartment number, etc., so there's not even a way to check this.
                    //if (strlen($street2) > 0) {
                    //    if (($street2 !== $respstreet2short) and ($street2 !== $respstreet2long)) {
                    //        $valid_input = false;
                    //    }
                    //}
                    //if (($city !== $respcityshort) and ($city !== $respcitylong)) {
                    //    $valid_input = false;
                    //}
                    if (($streetnumber !== $respstreetnumbershort) and ($state !== $respstreetnumberlong)) {
                        $valid_input = false;
                    }
                    if (($state !== $respstateshort) and ($state !== $respstatelong)) {
                        $valid_input = false;
                    }
                    if (($zip !== $respzipshort) and ($zip !== $respziplong)) {
                        $valid_input = false;
                    }
                }
            }
            if ($valid_input) {
                $result['is_valid'] = true;
                $result['message']  = '';
            } else {
                $result['is_valid'] = false;
                if (empty($respstreetnumberlong) or empty($respstreetnamelong) or empty($respcitylong) or empty($respstatelong) or empty($respziplong)) {
                    $result['message']  = empty( $field->errorMessage ) ? 'This is not a valid address. Please enter the address where you would like to receive gifts.' : $field->errorMessage;
                } else {
                    if (strlen($respstreet2long) > 0) {
                        $result['message']  = empty( $field->errorMessage ) ? 'This is not a valid address. Did you mean: ' . nl2br("\r\n") . $respstreetnumberlong . ' ' . $respstreetnamelong . ', ' . $respstreet2long . ', ' . $respcitylong . ', ' . $respstatelong . ' ' . $respziplong: $field->errorMessage;
                    } else {
                        $result['message']  = empty( $field->errorMessage ) ? 'This is not a valid address. Did you mean: ' . nl2br("\r\n") . $respstreetnumberlong . ' ' . $respstreetnamelong . ', ' . $respcitylong . ', ' . $respstatelong . ' ' . $respziplong: $field->errorMessage;
                    }                   
                }
            }
        }
    }
    GFCommon::log_debug( __METHOD__ . '(): Returning validation result.' );
    return $result;
}

`

This works for Gravity Forms address fields as it handles the entire block of address inputs as one form or input that are all combined and my code can go down in order and validate each snippet of information as it needs. I only have to call 'gform_field_validation_8_21' to reference the entire form of 5 distinct fields.

However, this is not the only place I need to validate address information: when a user signs up for my site, I have my account signup form intake not only name, age, user ID, and password, but also Address, city, state, zip, and phone. This info is then auto-populated onto the user's profile. **These fields are not run by Gravity Forms and are instead individual, single-line text fields. I need to learn how to gather these individual fields and put them into an array. This will allow me to feed my function the collection of address fields (address, city, state, zip, phone) so that it may validate them against the database. **

My issue is I do not know the proper hook names for these fields in php, or where I go to find these names. I have been using browser Inspect tools to find CSS selector names for items and then reverse engineer to the proper identifier for an individual element I need to manipulate. However, I have not been able to narrow these field selectors down. For example: the CSS selector for this one particular input field is #field_5 while its selector path is html body.xprofile.bp-user.my-account.my-profile.profile-edit.profile.edit.buddypress.bp-nouveau.page-template-default.page.page-id-0.page-parent.logged-in.admin-bar.paged-2.page-paged-2.theme-buddyboss-theme.woocommerce-js.buddyboss-theme.bb-template-v1.buddypanel-logo-off.bb-custom-typo.header-style-1.menu-style-standard.sticky-header.bp-location-autocomplete.bp-search.elementor-default.elementor-kit-475.customize-support.js.bb-page-loaded div#page.site div#content.site-content div.container div.bb-grid.site-content-grid div#primary.content-area.bs-bp-container main#main.site-main article#post-1504.bp_members.type-bp_members.post-1504.page.type-page.status-publish.hentry.user-has-earned div.entry-content div#buddypress.buddypress-wrap.bp-single-plain-nav.bp-dir-hori-nav div.bp-wrap.bp-fullwidth-wrap div.bb-profile-grid div#item-body.item-body div.item-body-inner div.bp-profile-wrapper div.bp-profile-content div.profile.edit form#profile-edit-form.standard-form.profile-edit.billing-address div.editfield.field_5.field_first-name.field_order_1.required-field.visibility-adminsonly.field_type_textbox fieldset input#field_5

To summarize, my two questions are: 1. How do I learn the proper php call to select the value of these individual input fields? 2. How do I take these values and assign them to an array that I may feed my function so it may read and validate these fields?

I have explored this question and this thread but still not sure if it is what I need.

Drew
  • 1
  • 1
  • 1. You do not select the values, the values are sent by the client to the server. 2. Either use array notation for input names like `name="address[postal_code]` etc. or just acces the fields from `$_POST` or `$_GET`. Also why dont you create a function `validateAddress(array $address): string` and call it wherever you have to validate addresses? – Code Spirit Oct 30 '22 at 21:15
  • https://stackoverflow.com/questions/3314567/how-to-get-a-form-input-array-into-a-php-array – Muhammad Ali Shah Oct 30 '22 at 22:07
  • @CodeSpirit Thank you so much and what is this function and how does it work? – Drew Oct 31 '22 at 16:02

0 Answers0