Last active
March 19, 2016 03:41
-
-
Save jazlopez/7fdb4e7b08d1f67ab19c to your computer and use it in GitHub Desktop.
Easy validation with symfony asserts
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
/** Use contraints **/ | |
use Symfony\Component\Validator\Constraints\Email; | |
use Symfony\Component\Validator\Constraints\Regex; | |
use Symfony\Component\Validator\Constraints\Url; | |
/** Snapshot of a controller class **/ | |
public function postAction(Request $request) | |
{ | |
$nameContainsErrors = $this->validator->validate($this->request->get('vendor_name'), new Regex(['pattern' => '/^[a-zA-Za0-9_-\s]+$/'])); | |
$urlContainsErrors = $this->validator->validate($this->request->get('vendor_url'), new Url()); | |
$emailContainsErrors = $this->validator->validate($this->request->get('vendor_email'), new Email()); | |
if ($nameContainsErrors->count()) { | |
$this->request->getSession()->getFlashBag()->add('error', | |
'Vendor name is not valid :' . $nameContainsErrors->get(0)->getInvalidValue()); | |
$this->request->getSession()->getFlashBag()->add('error', 'Vendor name allowed characters are case insensitive: a-z, digits: 0-9, whitespace, dash and underscore.'); | |
} | |
if ($urlContainsErrors->count()) { | |
$this->request->getSession()->getFlashBag()->add('error', | |
'Vendor URL is not valid: ' . $urlContainsErrors->get(0)->getInvalidValue()); | |
$this->request->getSession()->getFlashBag()->add('error', 'URL must start with http:// or https://'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment