Magento 2 – Add Validation for Existing Address Before Order Placement

checkoutonepage-checkoutorders

I added one custom field to customer's address & add validation when the customer adds the new address on checkout. And it's working perfectly.

But If I use an old existing address, that field is not there in the address, and the order place successfully.

So I want to add the validation if the field is empty if an existing address is used by the customer.

Best Answer

You can do this via obsever, here is how.

on your etc\events.xml

<event name="checkout_submit_before">
        <observer name="checkout_submit_before" instance="vendor\module\Observer\SubmitOrderBefore" />
    </event>

At Observers folder

<?php
    namespace vendor\module\Observer;
    
    use \Magento\Framework\Event\ObserverInterface;
    use \Magento\Store\Model\StoreManagerInterface;
    use Magento\Framework\App\Response\RedirectInterface;
    
    class SubmitOrderBefore implements ObserverInterface
    {   
        protected $resultRedirectFactory;
        protected $resource;
        
        public function __construct(
            \Magento\Framework\Controller\Result\RedirectFactory $_resultRedirectFactory,
            \Magento\Framework\App\ResourceConnection $_resource
        ) 
        {
            $this->resultRedirectFactory = $_resultRedirectFactory;
            $this->resource              = $_resource;
        }
        
        public function execute(
            \Magento\Framework\Event\Observer $observer
        )
        {
            $quote              = $observer->getEvent()->getQuote();
            $shippingAddress    = $quote->getShippingAddress();
            if(!isset($shippingAddress->getData('your_field_here'))
            {            
                exit;
            }                    
        }
    }
    ?>

This will redirect the client to the cart page when he hits the place order button on the final checkout step.