Skip to content

Instantly share code, notes, and snippets.

@ziadoz
Last active December 16, 2015 08:59
Show Gist options
  • Save ziadoz/5409711 to your computer and use it in GitHub Desktop.
Save ziadoz/5409711 to your computer and use it in GitHub Desktop.
Symfony Custom Form Basic Spam Validators
<?php
namespace Ziadoz\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
/**
* @Annotation
*/
class ContainsHtml extends Constraint
{
public $message = 'This value must not contain HTML markup.';
}
<?php
namespace Ziadoz\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ContainsLinksValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
$links = (int) (substr_count($value, 'http://') + substr_count($value, 'https://'));
if ($links > $constraint->max) {
$this->context->addViolation($constraint->message, array('%max%' => $constraint->max));
}
}
}
<?php
use Ziadoz\Validator\Constraints as CustomAssert;
$form = $app['form.factory']->createBuilder('form', array());
$form->add('message', 'textarea', array(
'constraints' => array(
new CustomAssert\ContainsHtml(),
new CustomAssert\ContainsLinks(array('max' => 4)),
),
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment