Validate cart before checkout

Let's continue exploring the Magento 2 events to achieve functionality that we need. In this post we will see how we can validate the cart before going to checkout.

To add a cart validation before going to checkout we will need the Magento event " controller_action_predispatch_checkout_index_index" which is called before we reach the checkout page.

As you can see the class instance that is defined to be used is the ValidateCartObserver. So on the observer class below where the execute function is the one that will be called, we add our validation.

So in that function we get the cart items quantity and if it is lower than 4 then we redirect to the cart with a custom message. So there will be the place to add your validation that you need.

Feel free to share this post and ask your questions in the comments below.

Till next time!

DigitalOcean Referral Badge