Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created April 7, 2015 23:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisguitarguy/2b27669a2e8d84d948ff to your computer and use it in GitHub Desktop.
Save chrisguitarguy/2b27669a2e8d84d948ff to your computer and use it in GitHub Desktop.
An example of standalone usage of the symfony validator component
/vendor/*
/composer.lock
# ignore certain files
*.pyc
*.swp
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
*.7z
# ignore compiled files
*.com
*.class
*.dll
*.exe
*.app
*.o
*.so
# system files
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
# ignore Sass cache
.sass-cache
{
"name": "chrisguitarguy/symfony-validation-example",
"description": "Standalone validator usage example.",
"keywords": ["symfony", "validator"],
"require": {
"php": ">=5.5",
"symfony/validator": "~2.6",
"symfony/config": "~2.6"
},
"autoload": {
"psr-4": {
"Chrisguitarguy\\ValidatorExample\\": "."
}
}
}
<?php
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\Validator\Validation;
use Chrisguitarguy\ValidatorExample\User;
$validator = Validation::createValidatorBuilder()
->setApiVersion(Validation::API_VERSION_2_5)
->addXmlMapping(__DIR__.'/validation.xml')
->getValidator();
$user = new User('notAnEmail', null);
$errors = $validator->validate($user);
foreach ($errors as $error) {
echo $error->getPropertyPath(), ': ', $error->getMessage(), PHP_EOL;
// or for debugging:
echo $error, PHP_EOL;
}
$validUser = new User('test@example.com', 'aPassword');
$errors = $validator->validate($validUser);
echo count($errors), PHP_EOL;
<?php
namespace Chrisguitarguy\ValidatorExample;
final class User
{
private $email;
private $password;
public function __construct($email, $password)
{
$this->email = $email;
$this->password = $password;
}
public function getEmail()
{
return $this->email;
}
public function getPassword()
{
return $this->password;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
<class name="Chrisguitarguy\ValidatorExample\User">
<property name="email">
<constraint name="NotBlank" />
<constraint name="Email" />
</property>
<property name="password">
<constraint name="NotBlank" />
</property>
</class>
</constraint-mapping>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment