I have added google recaptcha in my contact form. Also, I have added a contact form on CMS page.

I have to validate the captcha when post contact form.

I have to create a plugin for this, but not much idea how doing this. In plugin have to check condition with captcha. I fail to then add error, otherwise default success message from Magento.

  • Please first read my question properly
    – Magecode
    Commented Jul 6, 2018 at 9:45

1 Answer 1


At this,case you have to use around method (aroundExecute()).

First, create di.xml at app/code/{VendorName}/{Modulename}/etc/frontend/ for define plugin class.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type  name="Magento\Contact\Controller\Index\Post">
           <plugin name="add_new_item" sortOrder="1"  disabled="false"

Now, you have to create a plugin where you have to check captcha is valid or not at app/code/{VendorName}/{Modulename}/Plugin/


namespace StackExchange\Magentodemo\Plugin;

class ContactPostPlugin {

     * @var \Magento\Framework\UrlInterface
    protected $urlInterface;

     * @var \Magento\Framework\Message\ManagerInterface
    protected $messageManager;

    public function __construct(
        \Magento\Framework\Message\ManagerInterface $messageManager,
        \Magento\Framework\UrlInterface $urlInterface   
    ) {
        $this->messageManager = $messageManager;
        $this->urlInterface = $urlInterface;
    public function aroundExecute(
        \Magento\Contact\Controller\Index\Post $subject,
        \Closure $proceed          
        if({CapctheIsNOtValdated}) // condition for not valdate captcha
           $url = $this->urlInterface->getUrl('contact/index');
           $this->messageManager->addErrorMessage('Captcha is not valid');
           return $subject->getResponse()->setRedirect($url);            
        return $proceed();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.