WooCommerce Checkout Validation and Custom Field Sanitization

WooCommerce checkout validation and custom field sanitization

A custom checkout field needs three things: it is displayed, its value is validated before the order is created, and it is sanitized when it is saved. Each step has its own hook, and using the wrong one leads to orders placed with invalid data or errors shown twice. And since the block-based Checkout became the default for new stores, there are two checkouts with two different APIs.

Problem: A B2B store needs a VAT number on the checkout: optional in general, required for orders over €1,000, with a format check, saved with the order and shown in the admin and the emails.

Solution: For the classic (shortcode) checkout: add the field with woocommerce_billing_fields, validate in woocommerce_after_checkout_validation, save through the order object in woocommerce_checkout_create_order, and escape it on output. For the Checkout block: register it with the Additional Checkout Fields API.

Classic checkout

<?php
// 1. The field, after the company name
add_filter( 'woocommerce_billing_fields', function ( $fields ) {
    $fields['billing_vat_number'] = array(
        'label'       => __( 'VAT number', 'my-plugin' ),
        'placeholder' => __( 'e.g. DE123456789', 'my-plugin' ),
        'required'    => false,
        'class'       => array( 'form-row-wide' ),
        'priority'    => 35,
    );
    return $fields;
} );

function my_plugin_normalize_vat( $value ) {
    return strtoupper( preg_replace( '/[^A-Za-z0-9]/', '', (string) $value ) );
}

// 2. Validation: format and the business rule, with the other checkout errors
add_action( 'woocommerce_after_checkout_validation', function ( $data, $errors ) {
    $vat = my_plugin_normalize_vat( $data['billing_vat_number'] ?? '' );

    if ( '' !== $vat && ! preg_match( '/^[A-Z]{2}[A-Z0-9]{2,12}$/', $vat ) ) {
        $errors->add( 'vat_format', __( 'Please enter a valid VAT number, e.g. DE123456789.', 'my-plugin' ) );
    }

    if ( '' === $vat && (float) WC()->cart->get_total( 'edit' ) >= 1000 ) {
        $errors->add( 'vat_required', __( 'A VAT number is required for orders over €1,000.', 'my-plugin' ) );
    }
}, 10, 2 );

// 3. Save through the order object (works with HPOS)
add_action( 'woocommerce_checkout_create_order', function ( $order, $data ) {
    $vat = my_plugin_normalize_vat( $data['billing_vat_number'] ?? '' );
    if ( $vat ) {
        $order->update_meta_data( '_billing_vat_number', $vat );
    }
}, 10, 2 );

$data in both hooks is the checkout data WooCommerce has already collected and cleaned for the registered fields, so there is no need to read $_POST. Errors added to $errors appear in the list with the other checkout errors, and the order is not created. Normalizing (uppercase, no spaces and dots) before the check accepts “de 123.456.789” as well.

Show it

<?php
add_action( 'woocommerce_admin_order_data_after_billing_address', function ( $order ) {
    $vat = $order->get_meta( '_billing_vat_number' );
    if ( $vat ) {
        printf( '<p><strong>%s</strong> %s</p>', esc_html__( 'VAT number:', 'my-plugin' ), esc_html( $vat ) );
    }
} );

add_filter( 'woocommerce_email_order_meta_fields', function ( $fields, $sent_to_admin, $order ) {
    $vat = $order->get_meta( '_billing_vat_number' );
    if ( $vat ) {
        $fields['vat_number'] = array( 'label' => __( 'VAT number', 'my-plugin' ), 'value' => $vat );
    }
    return $fields;
}, 10, 3 );

The email templates escape the values of these fields themselves.

Checkout block

The classic hooks above do not run for the Checkout block: it sends the order through the Store API, not through the checkout form. For the block, WooCommerce has the Additional Checkout Fields API (WooCommerce 8.9+):

<?php
add_action( 'woocommerce_init', function () {
    if ( ! function_exists( 'woocommerce_register_additional_checkout_field' ) ) {
        return;
    }
    woocommerce_register_additional_checkout_field( array(
        'id'                => 'my-plugin/vat-number',
        'label'             => __( 'VAT number', 'my-plugin' ),
        'location'          => 'address',
        'type'              => 'text',
        'required'          => false,
        'sanitize_callback' => 'my_plugin_normalize_vat',
        'validate_callback' => function ( $value ) {
            if ( '' !== $value && ! preg_match( '/^[A-Z]{2}[A-Z0-9]{2,12}$/', $value ) ) {
                return new WP_Error( 'vat_format', __( 'Please enter a valid VAT number.', 'my-plugin' ) );
            }
        },
    ) );
} );

WooCommerce shows such a field in the block, saves it with the order and displays it in the admin and the emails. The “required over €1,000” rule depends on the cart, so for the block it needs a check on the Store API request as well; keep business rules like this in one PHP function used by both checkouts.

NOTE: Which checkout a store uses is visible on the Checkout page in the editor: a “Checkout” block or the [woocommerce_checkout] shortcode. Simpler field examples (a gift message) are in adding a custom checkout field.