Show Required Field Errors Inline on Checkout Page

How To Show Required Field Errors Inline on Checkout Required Fields.

 

On WooCommerce checkout page all error are shown on top of form as we can see this in image.
Before Adding inline error to required field first we need to get all the fields that are required and have labels.
After getting required field we need to add error message for it .

 

Now the question is how can we add error message to it?

We will do this in two steps:
1. Add Span Tag With Error Message, and set display none by default.
2. Show This Error When Form Is Submitted.

 

1. Add Span Tag With Error Message, and set display none by default.

 

We will use ‘woocommerce_form_field’ hook for it. Using this hook we can add a span containing error, before the closing label tag.

By default, this is set as display:none, which will be displayed via CSS later

 

function  CheckoutFieldsInlineError( $field, $key, $args, $value ) {
  if ( strpos( $field, '</label>') !== false && $args['required'] ) {
    $error = '<span class="error" style="display:none">';
    $error .= sprintf( __('%s is a required field.','woocommerce' ), $args['label'] );
    $error .= '</span>';
    $field = substr_replace( $field, $error, strpos( $field,'</label>'),0);
  }
return $field;
}
add_filter('woocommerce_form_field','CheckoutFieldsInlineError',99,4);

 

2. Show This Error When Form Is Submitted.

 

When form is submitted, the field which has an error ,WooCommerce will add “woocommerce-invalid-required-field” class to the parent “p” tag of input field. so we can use this as parent class and add css “display: block !important;” to show error msg.

 

<style>
.woocommerce-checkout p.woocommerce-invalid-required-field span.error {
   color: red;
   display: block !important;
   font-weight: bold;
}
<style>

 

Enjoy

Related Blogs

How To Create A Custom Product Tab On Product Page WooCommerce

To create a custom product tab on a WooCommerce product page, you’ll need to use some custom code. WooCommerce provides hooks and filters that allow you to extend and modify its functionality. Below are the steps to create a custom product tab in WooCommerce:

Top Quick View Plugins WooCommerce

There are several popular WooCommerce quick view plugins that provide a convenient way for customers to view product details without leaving the current page. Keep in mind that the popularity of plugins can change over time, so it’s a good idea to check for the latest information and reviews before making a decision.

Request A Quote

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.