A SlimPHP validator using respect validation package.
Via Composer
$ composer require terminusstudio/phpvalidator
Configuration
$config = [
'useSession' => false
];
useSession
- If set to true, validation results are saved in a session variable that can be accessed in the next request (using the ValidatorMiddleware). Defaults to false.
Using a container
Container::set('validator', function() {
return new \TS\PHPValidator\Validator($config);
});
Without container
$validator = new \TS\PHPValidator\Validator($config);
public function login($request, $response) {
if ($request->getMethod() == 'POST')
{
$v = Container::get('validator')->validate($request, [
'email' => v::noWhitespace()->notEmpty()->email(),
'password' => v::notEmpty()->length(8)->alnum('_'),
]);;
if($v->isValid())
{
//Do Processing
}
}
return View::render($response, 'login.twig');
}
The ValidatorMiddleware can be added to slim if you set the useSession to true in $config.
public function postLogin($request, $response) {
$v = Container::get('validator')->validate($request, [
'email' => v::noWhitespace()->notEmpty()->email(),
'password' => v::notEmpty()->length(8)->alnum('_'),
]);;
if($v->isValid())
{
//Do Processing
}
return $response->withHeader('Location', Router::getRouteParser()->urlFor('login.get'))->withStatus(302);;
}
If there were any errors, the next request will have access to the errors and values. To enable the middleware just add ValidatorMiddleware
class to the Slim app and pass the validator instance.
$app->add(new \TS\PHPValidator\ValidatorMiddleware(Container::get('validator')));
This plugin also supports Twig functions. To enable just add ValidatorTwig
when initializing twig. This requires slim/twig-view
package.
Container::set('view', function() {
$view = Twig::create(....);
// Add the validator extension and pass the validator instance to it
$view->addExtension(
new \TS\PHPValidator\ValidatorTwig(Container::get('validator'))
);
return $view;
});
There are currently 5 functions supported by the extension,
has_errors()
- Returns true if there are any errorshas_error($key)
- Returns true if$key
is invalidget_errors()
- Returns an array containing all errorsget_error($key, $toString = true)
- Returns an array containing all errors for a specific$key
. If$toString
is set to true, then it returns a string.get_value($key, $default = null)
- Returns the value for a specific$key
.
$key
is the field name set in the request.
{% if has_error('email') %}
{{ get_error('email') }}
{% endif %}
<input type="email" name="email" value="{{ get_value('email') }}">
The MIT License (MIT). Please see License File for more information.