Honeypot field in your form

24. Februar 2023TYPO3

The TYPO3 form framework includes a honeypot field by default. This tutorial shows you how to integrate such a field in your extension.

Keep in mind that a honeypot field is not a foolproof solution to avoid spam, it is just an approach to reduce spam and may need to be adjusted over time. Bots learn.

1. Add a text field

Add a normal text field to your form and make it invisible to the user. Fill the variable honeypot with a randomly generated string so that the bot cannot guess the field name. Also set the autocomplete to this value to prevent browsers from autofilling. Screen readers should also ignore this field, so set aria-hidden to true.

 

<f:form.textfield property="{honeypot}" id="{honeypot}"
                  additionalAttributes="{autocomplete: '{honeypot}', aria-hidden: 'true'}"
                  style="position:absolute; margin:0 0 0 -999em;" tabindex="-1" />

 

2. Add a rule in the model

Once the form has been submitted, you need to check that the honeypot field has been filled in. A human user won't do this because it's not visible to them. In this example, we use a demand object to receive the request. Therefore, we can extend the object with our honeypot variable and set a validator in the model.

 

/**
 * @Validate("Vendor\Example\Domain\Validator\HoneypotValidator")
 */
protected string $v5M9drzKRGCFVCQgNr89 = '';

 

/**
 * @return string
 */
public function getV5M9drzKRGCFVCQgNr89(): string
{
    return $this->v5M9drzKRGCFVCQgNr89;
}
/**
 * @param string $v5M9drzKRGCFVCQgNr89
 */
public function setV5M9drzKRGCFVCQgNr89(string $v5M9drzKRGCFVCQgNr89): void
{
    $this->v5M9drzKRGCFVCQgNr89 = $v5M9drzKRGCFVCQgNr89;
}

 

3. Create a validator

Create a validator class in Vendor\Example\Domain\Validator\HoneypotValidator.php and write your condition in the isValid function. In this case it is a simple check if the honeypot field has been filled in. If not, an error will be returned to the form.

 

class HoneypotValidator extends TYPO3\CMS\Extbase\Validation\Validator\AbstractValidator
{
    public function isValid($value)
    {
        if (!empty($value)) {
            $this->addError(
                $this->translateErrorMessage(
                    'validator.honeypot',
                    'example'
                ) ?? '',
                1677226962
            );
        }
    }
}

 

See also the Validation documentation: 
https://docs.typo3.org/m/typo3/reference-coreapi/main/en-us/ExtensionArchitecture/Extbase/Reference/Domain/Validator.html

4. Add to view

Assign the honeypot field name in the controller to the view.

 

$this->view->assign('honeypot', 'v5M9drzKRGCFVCQgNr89');