Moving the Add to Cart validation error message on product page

One quite often overlooked, but very important issue might happen because of design changes in the Add to Cart section on the Product Detail Page (PDP) in Magento 2.

This section is very likely to vary from project to project, but regardless of the scope of work and the volume of these changes, error validation on the Quantity field must not cause any issues whatsoever.

In this article, I will show you what needs to be done in such a case, which should be very easy and straightforward to implement in your custom theme. 🙂

Consider the following (and simplified) scenario – Add to Cart button is positioned on the right hand side of the Quantity field. You can achieve this with the following two CSS rules:

.box-tocart .fieldset {
    display: flex;
    align-items: center;
}
 
.box-tocart .actions {
    margin-left: 16px;
}

Show Add to cart button on the right hand side of quantity field

In case an error occurs (such as amount of 0 as Quantity), it will push the button away, which does not look good.

Error message pushes the add to cart button

You can resolve situation like this very easily by making two small changes in addtocart.phtml file in a custom theme:

  1. add HTML element with some specific ID (it will be used as target element once defined in step 2)
    <p id="qty-error-message"><?= $block->escapeHtml('Error message will appear here') ?></p>
  2. on input#qty element, add the following data attribute:
    <input id="qty" name="qty" type="number" ... data-errors-message-box="#qty-error-message" />

    Note that your selector as defined in data-errors-messsage-box must exist in your markup (this was done in step 1)

If you reload the page now, you should see the following:
Add placeholder element for error message

And if you generate the error (qty = 0), the button remains on same place. 🙂

Placeholder element shows error message

That’s it! Error message placeholder can be placed where ever you like, you are good to go as long as it is defined somewhere on the page. 🙂

Related Inchoo Services

You made it all the way down here so you must have enjoyed this post! You may also like:

Out of the box Form Validation in Magento Petar Sambolek
Petar Sambolek, | 24

Out of the box Form Validation in Magento

Magento form field AJAX validation Branko Ajzele
Branko Ajzele, | 8

Magento form field AJAX validation

Show Magento form validation error messages in a tooltip Hrvoje Jurisic
Hrvoje Jurisic, | 8

Show Magento form validation error messages in a tooltip

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.

Tell us about your project

Drop us a line. We'd love to know more about your project.