Puddinq.com sharing knowledge

Postcode check

Postcode check

<?php

namespace NewFountain\Skeleton\Forms;

class Postcode
{

    public function register()
    {
        // gravity validation
        add_action('gform_field_validation', [$this, 'validatePostcode'], 10, 4);

        // load script
        add_action('gform_enqueue_scripts', [$this, 'enqueueScripts']);

        // Postcode
        add_action('wp_ajax_postcode_lookup', [$this, 'lookupPostcode']);
        add_action('wp_ajax_nopriv_postcode_lookup', [$this, 'lookupPostcode']);
    }

    public function validatePostcode($result, $value, $form, $field)
    {

        if ($field->type != 'text' || !str_contains($field->inputName, 'postcode_id')) {
            return $result;
        }

        if ($result['is_valid'] === true && (empty($value) || preg_match('/^[1-9][0-9]{3}([A-RT-Z][A-Z]|[S][BCE-RT-Z])$/i', $value) === 0)) {
            $result['is_valid'] = false;
            $result['message'] = __('This is not a valid postcode.', 'ivn');
        }

        return $result;

    }

    public function lookupPostcode()
    {

        $result = $this->fetchPostcodeLookup($_POST['postcode']);
        wp_send_json($result, 200);

    }

    public function enqueueScripts()
    {
        $data = [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('postcode_lookup_nonce'),
        ];

        wp_enqueue_script(
            'postcode-lookup',
            get_stylesheet_directory_uri() . '/assets/js/dist/default/postcode.js',
            ['jquery'],
            nfc_getGitCommitHash(),
            true
        );

        wp_localize_script('postcode-lookup', 'postcodeLookup', $data);

    }

    private function fetchPostcodeLookup(string $postcode)
    {
        if (empty($postcode)) {
            return [];
        }

        $queryArguments = [
            'rows' => '1',
            'wt' => 'json',
            'q' => $postcode,
        ];

        $query = http_build_query($queryArguments);

        $args = [
            'headers' => [
                'accept' => 'application/json;charset=UTF-8',
            ],
        ];

        $response = wp_remote_get("https://geodata.nationaalgeoregister.nl/locatieserver/v3/free?{$query}", $args);
        $responseBody = wp_remote_retrieve_body($response);
        return json_decode($responseBody);

    }

}
// start one main function jQuery available as $, window available as root
(function ($, root) {
    'use strict';

    let postcodeInput;

    function updateResultFields(result)
    {
        jQuery('.gfield.straatnaam input').val(result.straatnaam);
        jQuery('.gfield.plaatsnaam input').val(result.woonplaatsnaam);
    }

    function getStreetForPostcode(postcode)
    {
        jQuery.ajax({
            url: postcodeLookup.ajax_url,
            type: 'post',
            data: {
                action: 'postcode_lookup',
                nonce: postcodeLookup.nonce,
                postcode: postcode
            },
            success: function (response) {
                let result = response.response.docs[0];
                if (result === undefined) {

                } else {
                    updateResultFields(result);
                }
            }
        })
    }

    function validatePostcode()
    {
        let postcode = $(this).val();
        if (postcodeInput !== postcode) {
            postcode = postcode.toUpperCase();
            postcode = postcode.replace(" ", "");
            $(this).val(postcode);
            postcodeInput = postcode;

            // only if 6 characters have been added
            if (postcode.length === 6) {
                // if format is 2034AB
                var reg = new RegExp("[1-9][0-9]{3}([A-RT-Za-rt-z][A-Za-z]|[sS][BCbcE-Re-rT-Zt-z])");
                var regResult = reg.exec(postcode);

                if (regResult === null || postcode !== regResult[0]) {
                    updateNoticeField();
                } else {
                    getStreetForPostcode(postcode);
                }
            }
        }
    }

    jQuery(document).on('gform_post_render', function (event, form_id) {

        if (form_id === 2) {
            jQuery(document).on('keyup', '.gfield.postcode input', validatePostcode);
        }
    });

})(jQuery, this);