Formit custom hook snippet validation - using hCaptcha

Hi all - Is it possible to use a custom hook snippet in a formit form to perform a jquery validation of a form element? I am using hCaptcha on a form and want to check the element has been completed before the form can be submited. The jQuery is as below:

$(“form”).submit(function(event) {

var hcaptchaVal = $(‘[name=h-captcha-response]’).value;
if (hcaptchaVal === “”) {
event.preventDefault();
alert(“Please complete the hCaptcha”);
}
});

I was hoping to run this from the custom hook snippet - but it doesnt want to work - I just get a blank white page on form submit - assuming the snippet falls over trying to execute the jQuery… Any thoughts on a solution here?

A hook snippet is to run PHP code on the server.
If you want to run Javascript code on the client, just include it with a <script> tag (in your chunk/template/resource-content) like any other js code.

I’m using hcaptcha as a Formit hook like this:

[[FormIt?
    &hooks=`hcaptcha, ...`
    ...]]

<div class="h-captcha" data-sitekey="[YOUR-SITE_KEY]"></div>

<script src='https://www.hCaptcha.com/1/api.js' async defer></script>

Then the hcaptcha Snippet:

<?php
$data = array(
  'secret' => "[YOUR-SECRET-KEY]",
  'response' => $_POST['h-captcha-response']
);$verify = curl_init();

curl_setopt($verify, CURLOPT_URL, "https://hcaptcha.com/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify); 
// var_dump($response);

$responseData = json_decode($response);
if($responseData->success) {
  return true;
} 
else {
  //$validator->addError('captcha','Captcha invalid.');
  $hook->addError('captcha','Error: Please complete the hCaptcha.');
  return false;
}
1 Like

Thanks - This seems to work nicely from a validation point of view - but if the hCaptcha is not completed - the error message is not being rendered. Can you advise how best to get the error message to appear?

It should be output to the general Formit error tag: [[!+fi.validation_error_message]]

Thanks - sorry, I was not using that in my form - added and works a treat.

1 Like

Dont suppose you have this working with quip as well do you?

Sorry, no. Does Quip use formit as well? If so, I would assume it should work the same? If not you probably have to revert back to a js version there.

This topic was automatically closed 2 days after discussion ended and a solution was marked. New replies are no longer allowed. You can open a new topic by clicking the link icon below the original post or solution and selecting “+ New Topic”.