WooCommerce: Display Required Field Errors “Inline” @ Checkout

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 CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 5
 * @community     https://businessbloomer.com/club/
 */ 

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

function bbloomer_checkout_fields_in_label_error( $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;
}

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;
}

Where to add custom code?

You should place custom PHP in functions.php and custom CSS in style.css of your child theme: where to place WooCommerce customization?

This code still works, unless you report otherwise. To exclude conflicts, temporarily switch to the Storefront theme, disable all plugins except WooCommerce, and test the snippet again: WooCommerce troubleshooting 101

Related content

  • WooCommerce: Cart and Checkout on the Same Page
    This is your ultimate guide – complete with shortcodes, snippets and workarounds – to completely skip the Cart page and have both cart table and checkout form on the same (Checkout) page. But first… why’d you want to do this? Well, if you sell high ticket products (i.e. on average, you sell no more than […]
  • WooCommerce: Disable Payment Method If Product Category @ Cart
    Today we take a look at the WooCommerce Checkout and specifically at how to disable a payment gateway (e.g. PayPal) if a specific product category is in the Cart. There are two tasks to code in this case: (1) based on all the products in the Cart, calculate the list of product categories in the […]
  • WooCommerce: Add Privacy Policy Checkbox @ Checkout
    Here’s a snippet regarding the checkout page. If you’ve been affected by GDPR, you will know you now need users to give you Privacy Policy consent. Or, you might need customer to acknowledge special shipping requirements for example. So, how do we display an additional tick box on the Checkout page (together with the existing […]
  • WooCommerce: Redirect to Custom Thank you Page
    How can you redirect customers to a beautifully looking, custom, thank you page? Thankfully you can add some PHP code to your functions.php or install a simple plugin and define a redirect to a custom WordPress page (as opposed to the default order-received endpoint). This is a great way for you to add specific up-sells, […]
  • WooCommerce: Disable Payment Gateway by Country
    You might want to disable PayPal for non-local customers or enable a specific gateway for only one country… Either way, this is a very common requirement for all of those who trade internationally. Here’s a simple snippet you can further customize to achieve your objective. Simply pick the payment gateway “slug” you want to disable/enable […]

Rodolfo Melogli

Business Bloomer Founder

Author, WooCommerce expert and WordCamp speaker, Rodolfo has worked as an independent WooCommerce freelancer since 2011. His goal is to help entrepreneurs and developers overcome their WooCommerce nightmares. Rodolfo loves travelling, chasing tennis & soccer balls and, of course, wood fired oven pizza. Follow @rmelogli

88 thoughts on “WooCommerce: Display Required Field Errors “Inline” @ Checkout

  1. I just want to say thank you for the wonderful snippets you provide. These have been very helpful and educational.

    I am surprised that WooCommerce team don’t just implement some of the features you snippets provide as feature of WooCommerce.

    Your snippets – like this one has helped me overcome the need to find a way to scroll to the top on error messages – which WooCommerce does poorly – because the notifications are way above where the scroll stops – so customers don’t even see what the error is.

  2. snippet only work for required area, what about the postcode area if entered invalid?
    this error message can not move it. I tried so many ways..

    Shipping ZIP Code is not a valid postcode / ZIP.

  3. Hiya,

    I’ve added the CSS into the child theme style.css file

    I’ve added the PHP using Code snippets

    and it’s almost working!

    The inline is displaying as it should, but the errors still show at the top

    What have I done wrong?

    Many Thanks

    Jon

    1. Hi Jon! It could be because of your custom checkout HTML, so possibly your theme or a plugin. CSS or PHP may need slight changes to make it work with your custom setup

  4. Hello there, grat snippet and very useful. Is it possible to display the inline errors, only AFTER having submitted the form?

    1. I guess that’s possible, yes

  5. Worked perfectly for me.

    The only thing is that for me it also still shows all the missing fields at the top. Not the biggest problem but it looks better if these were hidden.

    1. You can easily remove them via CSS (not ideal, yet easy):

      form.checkout > .woocommerce-NoticeGroup-checkout {
         display: none;
      }
      
  6. hey.. Not working in my site I have done the same but still error is not showing .When i inspect the span tag is added in the form with display:none but error in red is not appearing please suggest and replay.

    1. It could be your CSS needs adjusting because (possibly) your theme uses custom WooCommerce CSS

  7. Doesn’t Work as of 22 Nov 2021
    The Second Part Snippet gives Fatal Error on the site

    1. What does the error say?

  8. Hi

    This works on all my fields except tel number and also an extra field that I put in (using the plug in Checkout Field Editor) . Both are required.

    Wood mart theme

    Thanks

    1. Hi Amy, this will work on all fields that are required + have been created with the default woocommerce_form_field() function. Otherwise it won’t work or may need some customization

  9. I just created a gist with the ability to add custom error messages as inline messages to the woocommerce checkout form at the validation steps. Maybe it’s a useful extension for people reading this article, so as I did.

    https://gist.github.com/lucasjahn/2da5405d3bd7d3e12555e902c25ed784

  10. Only works for empty field validation. Doesn’t work for other validation (eg: wrong email format).

    Is it possible to have a dynamic message instead of having “is a required field” phrase?

    1. Hey R, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  11. Works for name and email fields.
    Oddly does not work for street address, city or zip fields.

    1. Odd! Should work for all fields that have a label and are required

  12. Como se podria hacer para que se muestre debajo del input y no encima gracias

    1. Hi there, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  13. Thanks so much sire much helpful

    1. Welcome sire

  14. I just used it (sept. 2020) , and ir worked perfectly for me.

    Thank you very much!!

    1. Great!

  15. Example didn’t work with the TwentyTwenty theme, I replaced the line

    $field = substr_replace( $field, $error, strpos( $field, ‘</label' ), 0);
    with
    $field = substr_replace( $field, $error, strpos( $field, '</span' ), 0);

    So, it adds the error message right after the input field.

    1. Nice

  16. Hi Rodolf,

    What about invalid fields validation? if I type an incomplete email e.g. “rodolf@” the error message is not shown above the field. How can I make that work in the same way as the required fields?

    1. Hi Diogo, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  17. Awesome thanks. Would it not be better to only load this on the checkout page (performance wise)?
    if checkout load.. Or why do you load it on all pages?

    1. Sure, you’re right, it can be done. But also if you wish to make it work on other pages, the code is already done for you and just need to add more CSS

  18. It does nothing 10-01 2020 – can you issue an update? Thanks! ๐Ÿ™‚

  19. Hello

    Not working on the latest version of wc and wordpress + Multisteps checkout.

    1. This only works with the default Woo checkout, sorry

  20. That works well, except for the Terms and conditions checkbox… Anyone found a fix yet? ๐Ÿ™‚

    1. Hi Alex, I guess T&C are not really a field but just a checkbox on the checkout page, so it will need custom code for that

      1. Has anyone found the fix to show the error message inline with the terms and conditions box? Thanks!!!

  21. This code is just what I need but it has no effect. Tokoo theme is not using it’s own template. All files are up to date. Can you help figure out why this doesn’t work?

    1. Hello Sharon, it could be due to your fields HTML, and the way labels and inputs are nested into each other. Custom troubleshooting might be needed, sorry!

      1. If you can give me a sense of your fees, I may be able to request your custom fix.

        1. Thank you Sharon, feel free to contact me here and we can have a chat

  22. Hey, what a great find!
    thank you for the info, can you help me figure out how do I remove the whole list of errors at the top part of the form?
    I.E.
    Billing Last name is a required field.
    Billing Street address is a required field.
    Billing Postcode / ZIP is a required field.
    Billing Phone is a required field.
    Billing Email address is a required field.
    etc etc…

    Thank you!

    1. Hello Yig, thanks so much for your comment! Yes, this is definitely possible, but I’m afraid it’s custom work. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding!

  23. Thanks! I’ve used this code to display inline errors.

    I am facing one problem like the inline errors are not displaying for some of the fields (Like Street address, Town / City, Postcode / ZIP). Can you please let me know about it?

    Thanks,
    Kakshak

    1. Hi Kakshak thanks for your comment! Which fields are not working, and for which country?

      1. Hi,

        I added the following to my functions file to de-register the problematic script (wc-address-i18n):

        function deregister_woocommerce_assets() {
            // array of script handlers that we can disable so that we can 
            // build them with grunt manually
            $scripts_to_remove = array(
                'wc-address-i18n',
            );
        
            foreach ($scripts_to_remove as $script) {
                wp_deregister_script($script);
                wp_register_script($script, null, array('jquery'), null, true);
            }
        }
        add_action('wp_print_scripts', 'deregister_woocommerce_assets', 100);
        

        All works perfectly now – Thank you

        1. Awesome!

          1. Thank you Steve. I had the same problem, added your code and it works perfectly now.

  24. Rodolfo,

    I have the your solution but have found that the inline validations only work for the woocomerce form fields and not for the billing fields.
    Can you help me out in also adding the inline validations to the billing fields on the checkout form.

    Thanks,
    RIya

    1. Hi Riya, this will work for all fields that use “woocommerce_form_field”. If you added custom fields not using this, it won’t show.

  25. This is working, but I want to move this to be outside the . Is this possible?

    Why? Because I hide the label (I use placeholders instead) and want only the error message to appear.

    1. Hello Fabian, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  26. Thanks, great idea! Having one issue though, am using the code with a child version of Oceanwp SHOP template and the original error bar at the top still appears.

    Am assuming the style=”display:none” in the pp code should turn this off? If it should then its not happening for me ๐Ÿ™

    1. Thank you Sven ๐Ÿ™‚ Yes, this does not hide the error message above, so you’ll need to find a workaround indeed. Good luck!

  27. Hi, Super useful information, thank you so much!

    I did have a strange issue. The Street, City and Postcode/Zip would not show the inline message. But other fields such as Name, Phone and Email would work fine.

    Basically, the

    <span class="error" style="display:none">...</span>

    was not being rendered on the page for some fields. After much searching and trial and error I discovered that the javascript in the file assets/js/frontend/address-i18n.min.js is targeting specifically those fields that are having issues.

    I replaced the content of the i18n file with an empty jQuery function and all the validation messages were showing. It works for my site because it’s uni-lingual. If someone needs to use localization they might need to dig into that file and see why the issue is happening.

    I just wanted to mention that in case someone else has the same issue. I hope it will save them several hours searching for the issue.

    Thanks again for the great information!
    Kindest Regards

    1. Thank you!

    2. I have the same problem with address-i18n.min.js. Fixed this by disabling these scripts via

      wp_deregister_script ('wc-address-i18n');

      .

      Rodolfo thank you very much for the snippet.

    3. Hurried with the answer.
      “wp_deregister_script” caused other problems
      Everything worked after I added inside my JS – wc_address_i18n_params = null;

      1. Nice!

      2. Hi Max,

        wc-address-i18n has created a lot of problem in website after I deregister it, now I am not able to recover properly. Can you please suggest, what did you do to recover it?

  28. Thanks as always for the great snippets!
    Is there any way to pair this with your ‘Confirm e-mail address’ snippet?
    Currently this works for missed fields, but the mismatched e-mail notice still appears at the top of the page.

    1. Hey Andy, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. If you’d like to get a quote, feel free to contact me here. Thanks a lot for your understanding! ~R

  29. Thanks. very useful. Is there a way to show errors when phone number field email field is not filled correctly.

    1. Hey Hajer, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

  30. In phone version, my user cannot see the error, could you please use a function to slide back to the error field ?

    1. Ismail, thanks so much for your comment! Yes, this is possible – unfortunately this is custom work and I cannot provide a complementary solution here via the blog comments. Thanks a lot for your understanding! ~R

    2. Hello Ismail .
      I am facing same issue as yours , did you manage to find a solution for it ? thanks in advance

  31. Very nice code to use.

    It would be even a must if it also would message out the “accept the terms and conditions” part on the checkout

    1. Thanks ๐Ÿ™‚

  32. Rodolfo,

    I’m just commenting because I’m on mobile and don’t see any other way to subscribe to your blog!

    Maybe I’m missing something, but I think it could be a bit more obvious if getting readers is one of your goals

    1. Joe, thanks for your comment! Yes you’re right, the pop up is disabled on mobile. You can join the newsletter by watching any of my free videos e.g. https://businessbloomer.com/woocommerce-customization-hangout/

  33. Rodolfo, You made my day. Thanks for providing this information at the right time.

    1. Thank you Chuks ๐Ÿ™‚

  34. Thank you for the code Rodolfo, unfortunately it does not work on my theme (Flatsome).

    On your code I can see that the errors should be under .woocommerce-checkout p.woocommerce-invalid-required-field span.error but that is not the case for me. In my case, the error notices are displayed under .woocommerce-notices-wrapper .woocommerce-NoticeGroup-checkout ul. Here is the code from the source:

    Billing First name is a required field.
    …..
    …..
    Create account password is a required field.
    Please read and accept the terms and conditions to proceed with your order.

    Any idea on how to make this work?

    1. Resending the coded html as the first one is not showing right:

       <div class="woocommerce-notices-wrapper">
      <div class="woocommerce-NoticeGroup woocommerce-NoticeGroup-checkout">
      <ul class="woocommerce-error" role="alert">
      <li><strong>Billing First name</strong> is a required field.</li>
      ....
      ....
      <li><strong>Create account password</strong> is a required field.</li>
      <li>Please read and accept the terms and conditions to proceed with your order.</li></ul></div></div>
      1. Hey Kensai, my snippet does not affect the notice that is above the Checkout – it adds errors above each field instead ๐Ÿ™‚

    2. My mistake I can now see what it should do. Still, on Flatsome it does not work as intended. If I forget to add a field, and mouse click on checkout it does nothing. But, if I press Enter instead of checkout then all “forgotten” fields show up with red.

      1. Flatsome probably has a customized WooCommerce checkout template, so you’ll need to re-adapt the coding. Sorry ๐Ÿ™‚

  35. Rodolfo,

    Very nice! I implemented on two of my ecommerce sites.

    Thank you,

    Javier

    1. Awesome ๐Ÿ™‚

  36. Rodolfo, you are my hero! I’ve learned more about woocommerce structure from your code than any other resource. Keep up the fine work! We’ve had some customers complaining about problems with the orders, I bet half just missed a field and didn’t see which field it was. This is a beautiful addition. Thanks again!

    1. Thank you Ed ๐Ÿ™‚

  37. Thank you for this. I had on this weeks to do list to address this very issue. Uncanny timing!! It has to be hands down one of the most popular complaints we have from woocommerce customers.

    One other thing I’d like to add that’s just as popular, perhaps fodder or a second post or addendum to this one.

    The “Checkout Process Spinny Indicator “graphic, (I don’t know what it’s called) is also at the top of the screen and is completely out of view for laptops and smaller screens when someone click the checkout button. I always felt that that graphic should be beside or above the button so you can see it in action. Otherwise, so many people complain that they didn’t know anything happened after pressing it. Would that be part of this code or would that be a different approach?

    Great article as always. Thanks again!

    Blue

    1. Hey Blue, thanks a lot ๐Ÿ™‚ You could just try to center align that spinner on the screen with CSS – not 100% sure. It’s not related to this though, so if you figure something out I’ll create another post. Cheers!

Questions? Feedback? Customization? Leave your comment now!
_____

If you are writing code, please wrap it like so: [php]code_here[/php]. Failure to complying with this, as well as going off topic or not using the English language will result in comment disapproval. You should expect a reply in about 2 weeks - this is a popular blog but I need to get paid work done first. Please consider joining the Business Bloomer Club to get quick WooCommerce support. Thank you!

Your email address will not be published. Required fields are marked *