Last active
December 16, 2015 08:59
-
-
Save ziadoz/5409711 to your computer and use it in GitHub Desktop.
Symfony Custom Form Basic Spam Validators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Ziadoz\Validator\Constraints; | |
use Symfony\Component\Validator\Constraint; | |
/** | |
* @Annotation | |
*/ | |
class ContainsHtml extends Constraint | |
{ | |
public $message = 'This value must not contain HTML markup.'; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Ziadoz\Validator\Constraints; | |
use Symfony\Component\Validator\Constraint; | |
/** | |
* @Annotation | |
*/ | |
class ContainsLinks extends Constraint | |
{ | |
public $message = 'This value must not contain more than %max% links.'; | |
public $max = 2; | |
/** | |
* {@inheritDoc} | |
*/ | |
public function getDefaultOption() | |
{ | |
return 'max'; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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