Home » WooCommerce: Display Required Field Errors “Inline” @ Checkout

WooCommerce: Display Required Field Errors “Inline” @ Checkout

by Tutor Aspire

If you’re familiar with the upcoming Gutenberg editor, you’ll know there have been a million doubts in regard to accessibility. So, accessibility matters – and WooCommerce has a few issues as well.

One interesting accessibility fix is the error notification system on the checkout page. Yes, the missing fields error show on top of the page when trying to place an order, but once you scroll down to fill them out again you might need a reminder of which field is missing without having to scroll back up to check the error.

This is quite difficult to explain, so take a look at the screenshot. The suggestion here is to also add “inline” error notifications (“XYZ is a required field“) right above each field, so that the user knows exactly what to do. So, let’s see how it’s done.

Displaying inline “required field” errors @ WooCommerce Checkout

Snippet Part 1 (PHP): Print Required Field Errors Inline @ WooCommerce Checkout

The first part is a PHP workaround. We basically go searching for all those fields that have a label and are required, and just before the closing label tag we add a span containing the error.

By default, this is set as display:none, which will be displayed as block and therefore made visible via CSS later on (Snippet 2).

/**
 * @snippet       Add Inline Field Error Notifications @ WooCommerce Checkout
 * @how-to        Get tutoraspire.com FREE
 * @author        Tutor Aspire
 * @compatible    WooCommerce 5
 * @donate $9     https://tutoraspire.com
 */ 

add_filter( 'woocommerce_form_field', 'tutoraspire_checkout_fields_in_label_error', 10, 4 );

function tutoraspire_checkout_fields_in_label_error( $field, $key, $args, $value ) {
if ( strpos( $field, '' ) !== false && $args['required'] ) {
$error = '';
$field = substr_replace( $field, $error, strpos( $field, '' ), 0);
}
return $field;
}

Snippet Part 2 (CSS): Display Required Field Errors Inline @ WooCommerce Checkout

Now that those spans are printed on the page, we need to display them in case users go place the order but forget to fill out a required field.

This is usually done via JavaScript validation… but WooCommerce already does that for us 🙂

WooCommerce JS adds a CSS class called “woocommerce-invalid-required-field” to a required field that is not filled out.

Each field will be getting this class and generate an error. So, thankfully, we need no JS for showing those hidden spans, we can simply target the class!

.woocommerce-checkout p.woocommerce-invalid-required-field span.error {
color: #e2401c;
display: block !important;
font-weight: bold;
}

You may also like