I created a custom registration form, one of the fields is being validated using a third party API.

If the field passes validation later I update_user_meta.

Currently if the field fails validation I add an error using wc_add_notice().

The problem is, I need to do something different depending on if it failed because the data didn't pass validation or it failed because the API is down. I have the logic to tell which fail it is, I'm just not sure what to do with it.

Here is a sample of my validation function.

function add_registration_validation($username, $email, $validation_errors) {       
    $billing_npi = sanitize_text_field($_POST['billing_npi']);

    if (isset($_POST['billing_npi']) && empty($_POST['billing_npi'])){ // empty
        $validation_errors->add('billing_npi_error', __(' NPI is required!', 'woocommerce'));
        // NPI API Validation
        $npiURL = 'https://npiregistry.cms.hhs.gov/api/?number=' . $billing_npi . '&version=2.1';
        $add_order_response = wp_remote_get($npiURL);

        if (is_array($add_order_response) && !is_wp_error($add_order_response)) {

            // Failed So Send Error 

           $json_decoded_add_order_response = json_decode($add_order_response['body']);

            if ($json_decoded_add_order_response->result_count < 1) {
                $validation_errors->add('billing_npi_error', __(' Your NPI number does not match our records!', 'woocommerce'));

            // Failed Because API is down

            // holds error msg
            // $error_string = $add_order_response->get_error_message();


    return $validation_errors;

add_action('woocommerce_register_post', 'add_registration_validation', 10, 3);

You can see in the comments the 2 different fail types.

What I need to happen is this...

If it fails because it didn't match the API I throw an error stopping the form from submitting, which is working fine.

But if it fails because the API is down, I want to submit the form as normal but create a flag letting me know the API was down at the time. I think I need to set a variable and update a hidden input, but can't figure out how to do this.

Here is how I am saving the data.

function add_registration_meta($customer_id) {
    if (isset($_POST['billing_npi'])) {
        update_user_meta($customer_id, 'billing_npi', sanitize_text_field($_POST['billing_npi']));

add_action('woocommerce_created_customer', 'add_registration_meta');

Hopefully that makes sense! I'm open to any suggestions, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.