Honeypot for Zend Framework

on April 21, 2010. in Development, Programming. A 1 minute read.

I just hacked up a little code snippet based on Matthew’s Honeypot Wordpress plugin. It’s basically just a Validator for a Zend Form element which is hidden from the user via CSS. Cause it’s hidden, users won’t see it, but spambots will, well, cause they are bots.

If the element is left empty, it’s valid, otherwise it’s not.

So, here’s the code:

<?php
class App_Validate_Honeypot extends Zend_Validate_Abstract
{
    const SPAM = 'spam';

    protected $_messageTemplates = array(
        self::SPAM => "I think you're a spambot. Sorry."
    );

    public function isValid($value, $context=null)
    {
        $value = (string)$value;
        $this->_setValue($value);

        if(is_string($value) and $value == ''){
            return true;
        }

        $this->_error(self::SPAM);
        return false;
    }
}

I add the element to the form like this:

<?php
$this->addElement(
    'text',
    'honeypot',
    array(
        'label' => 'Honeypot',
        'required' => false,
        'class' => 'honeypot',
        'decorators' => array('ViewHelper'),
        'validators' => array(
            array(
                'validator' => 'Honeypot'
            )
        )
    )
);

There. Done.

Happy hackin’!