+ All Categories
Home > Software > Introdução ao Respect\Validation (1.0)

Introdução ao Respect\Validation (1.0)

Date post: 13-Apr-2017
Category:
Upload: henrique-moody
View: 585 times
Download: 0 times
Share this document with a friend
24
Respect\Validation O mais incrível mecanismo de validação já criado para PHP
Transcript
Page 1: Introdução ao Respect\Validation (1.0)

Respect\ValidationO mais incrível mecanismo de validação já criado para PHP

Page 2: Introdução ao Respect\Validation (1.0)

Sobre• Biblioteca de validação criada por Alexandre Gaigalas (Alganet)

• PHP 5.3+ e HHVM 3.3+

• Interface fluente

• Mais de 100 regras de validação

• Mais de 175 mil instalações via Composer

• Média de 13 mil instalações por mês via Composer

Page 3: Introdução ao Respect\Validation (1.0)

Exemplo

Page 4: Introdução ao Respect\Validation (1.0)

• Obter dados via $_POST

• Validar se a chave “email” é um email válido

• Exibir mensagem de erro

Page 5: Introdução ao Respect\Validation (1.0)

Validator - Zenduse Zend\InputFilter\Input;use Zend\InputFilter\InputFilter;use Zend\Validator\EmailAddress;

$email = new Input('email');$email->getValidatorChain() ->attach(new EmailAddress());

$inputFilter = new InputFilter();$inputFilter->add($email) ->setData($_POST);

if (!$inputFilter->isValid()) { foreach ($inputFilter->getMessages() as $messages) { echo current($messages); break; }}

Page 6: Introdução ao Respect\Validation (1.0)

Validation - Illuminateuse Illuminate\Validation\Factory;use Symfony\Component\Translation\Translator;

$factory = new Factory(new Translator('en'));$validator = $factory->make( $_POST, array('email' => 'required|email'));

if ($validator->fails()) { echo $validator->messages()->first();}

Page 7: Introdução ao Respect\Validation (1.0)

Validator - Symfonyuse Symfony\Component\Validator\Validation;use Symfony\Component\Validator\Constraints as Assert;

$constraint = new Assert\Collection(array( 'email' => new Assert\Email(),));

$validator = Validation::createValidator();$violations = $validator->validateValue($_POST, $constraint);if (count($violations) > 0) { echo $violations;}

Page 8: Introdução ao Respect\Validation (1.0)

Validation - Respectuse Respect\Validation\Validator as v;

try { v::key('email', v::email())->check($_POST);} catch (Exception $exception) { echo $exception->getMessage();}

Page 9: Introdução ao Respect\Validation (1.0)

Validando

Page 10: Introdução ao Respect\Validation (1.0)

Método validate()if (!v::email()->validate($input)) { // ...}

Page 11: Introdução ao Respect\Validation (1.0)

Método check()try { v::stringType()->length(2, 15)->check(0);} catch (Exception $exception) { echo $exception->getMessage();}

// Resultado://// 0 must be a string

Page 12: Introdução ao Respect\Validation (1.0)

Método check()try { v::stringType()->length(2, 15)->check('A');} catch (Exception $exception) { echo $exception->getMessage();}

// Resultado://// "A" must have a length between 2 and 15

Page 13: Introdução ao Respect\Validation (1.0)

Método assert()try { v::stringType()->length(2, 15)->assert(0);} catch (NestedValidationExceptionInterface $exception) { echo $exception->getFullMessage();}

// Resultado://// \-All of the required rules must pass for 0// |-0 must be a string// \-0 must have a length between 2 and 15

Page 14: Introdução ao Respect\Validation (1.0)

E se eu quiser…

Page 15: Introdução ao Respect\Validation (1.0)

Não utilizar estáticosuse Respect\Validation\Rules;use Respect\Validation\Validator;

$validator = new Validator();$validator->addRule(new Rules\Key('email', new Rules\Email()));$validator->assert($_POST);

Page 16: Introdução ao Respect\Validation (1.0)

Reutilizar cadeia de validação$validator = v::stringType()->length(2, 15);

$validator->assert($input1);$validator->assert($input2);$validator->check($input3);

if ($validator->validate($input4)) { // ...}

Page 17: Introdução ao Respect\Validation (1.0)

Obter as mensagens em formato de array

try { v::stringType()->length(2, 15)->assert(0);} catch (NestedValidationExceptionInterface $exception) { print_r($exception->getMessages());}

// Resultado://// Array// (// [0] => 0 must be a string// [1] => 0 must have a length between 2 and 15// )

Page 18: Introdução ao Respect\Validation (1.0)

Traduzir mensagenstry { v::stringType()->length(2, 15)->check(0);} catch (Exception $exception) { $exception->setParam('translator', 'gettext'); // ...}

Page 19: Introdução ao Respect\Validation (1.0)

Customizar mensagens1

try { v::stringType()->length(2, 15)->assert(0);} catch (NestedValidationExceptionInterface $exception) { $messages = $exception->findMessages(array( 'stringType' => 'Valor precisa ser uma string', 'length' => 'Valor precisa conter de 2 a 15 caracteres', )); print_r($messages);}

// Resultado://// Array// (// [stringType] => Valor precisa ser uma string// [length] => Valor precisa conter de 2 a 15 caracteres// )

Page 20: Introdução ao Respect\Validation (1.0)

Customizar mensagens2

try { v::key('email', v::email())->assert(0);} catch (NestedValidationExceptionInterface $exception) { $messages = $exception->findMessages(array( 'email' => ‘Você precisa fornecer um email válido' )); print_r($messages);}

// Resultado://// Array// (// [email] => Você precisa fornecer um email válido// )

Page 21: Introdução ao Respect\Validation (1.0)

Utilizar minhas próprias regrasv::with('My\\Validation\\Rules\\');v::myRule(); // Tenta carregar "My\Validation\Rules\MyRule" se existir

Page 22: Introdução ao Respect\Validation (1.0)

Trabalhar com valores opcionaisv::optional(v::email())->validate(''); // truev::optional(v::email())->validate(null); // true

Page 23: Introdução ao Respect\Validation (1.0)

Inverter uma regrav::not(v::equals('foo'))->validate('bar'); //truev::not(v::equals('foo'))->validate('foo'); //false

Page 24: Introdução ao Respect\Validation (1.0)

Obrigado


Recommended