Showing results for 
Search instead for 
Did you mean: 

Magento 2 native captcha add to custom form

Magento 2 native captcha add to custom form

Hello everyone!


Just looked similar solutions here and googled, but haven't find.

I created custom page 'Custom contact us' in admin panel with form like:

  <form action="/action/page">

    <label for="fname">First Name</label>
    <input type="text" id="fname" name="firstname" placeholder="Your name..">

    <label for="lname">Last Name</label>
    <input type="text" id="lname" name="lastname" placeholder="Your last name..">

    <label for="subject">Subject</label>
    <textarea id="subject" name="subject" placeholder="Write something.." ></textarea>

<!-- I'd like to add native captcha-->
    <input type="submit" value="Submit">

But I'd like the simpliest way to add native magento 2 captcha.


I see only difficult and huge solutions as creating new module etc. But I believe, the native captcha could be added by widget or something like that.





Re: Magento 2 native captcha add to custom form

Hello @faltsmanyae1f9 


For adding google recaptcha into your custom form, you have to get the site key and secret key for your domain from


First call the google recaptha javascript file in your header. Add the recaptcha js in your respective layout file as coded below.


<page xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<script src="" src_type="url" />

Then add the below code in your custom form before end of </form> tag. (to display captcha in bottom)


<div class="g-recaptcha" data-sitekey="<--your site key-->"></div>

 Now you can able to see captcha displayed in your form. But the user response is not verified yet.To make it happen, do below code changes in your Save action controller.


namespace Munesh\SampleModule\Controller;

class Save extends \Magento\Framework\App\Action\Action{
* @var Google reCaptcha Options
private static $_siteVerifyUrl = "";
private $_secret;
private static $_version = "php_1.0";
* Save Form Data
* @return array
public function execute()
{$captcha = $this->getRequest()->getParam('g-recaptcha-response');$secret = "<--your secret key-->"; //Replace with your secret key$response = null;$path = self::$_siteVerifyUrl;$dataC = array (
'secret' => $secret,
'remoteip' => $_SERVER["REMOTE_ADDR"],
'v' => self::$_version,
'response' => $captcha);$req = "";
foreach ($dataC as $key => $value) {     $req .= $key . '=' . urlencode(stripslashes($value)) . '&';
// Cut the last '&'$req = substr($req, 0, strlen($req)-1);$response = file_get_contents($path . $req);$answers = json_decode($response, true);
if(trim($answers ['success']) == true) {
    // Captcha Validated
    // Save Form Data
    // Dispay Captcha Error


Make sure you have replaced the site key and secret key in the above sample codes.

Find helpful ? Consider Giving Kudos to this post.
Problem solved? Click Accept as Solution!"