SlideShare une entreprise Scribd logo
1  sur  77
Télécharger pour lire hors ligne
Domine
                 Validação de Dados
                      em 45min




30 de Novembro        PHP Conference 2012   1
Alexandre Gaigalas
                 http://about.me/alganet




30 de Novembro          PHP Conference 2012   2
@alganet




30 de Novembro    PHP Conference 2012   3
Alfanumérico



                          @alganet




30 de Novembro             PHP Conference 2012   4
Alfanumérico                          Aceita _



                          @alganet




30 de Novembro             PHP Conference 2012              5
Alfanumérico                          Aceita _



                          @alganet

            Sem espaços




30 de Novembro             PHP Conference 2012              6
Alfanumérico                             Aceita _



                          @alganet

            Sem espaços                          1-15 caracteres




30 de Novembro             PHP Conference 2012                     7
/^[[:alnum:]_]{1,15}$/
                      (Expressão Regular)

           Alfanumérico                             Aceita _



                          @alganet

            Sem espaços                          1-15 caracteres




30 de Novembro             PHP Conference 2012                     8
/^[[:alnum:]_]{1,15}$/

           Alfanumérico                            Aceita _



        @alexandre_gomes_gaigalas

            Sem espaços                         1-15 caracteres




30 de Novembro            PHP Conference 2012                     9
/^[[:alnum:]_]{1,15}$/

           Alfanumérico                             Aceita _



                          @al-ga-net

            Sem espaços                          1-15 caracteres




30 de Novembro             PHP Conference 2012                     10
/^[[:alnum:]_]{1,15}$/

           Alfanumérico                            Aceita _



                 @Alexandre Gomes

            Sem espaços                         1-15 caracteres




30 de Novembro            PHP Conference 2012                     11
E se eu quiser exibir os erros?




30 de Novembro     PHP Conference 2012    12
if (!ctype_alnum(str_replace('_', '', $username)))
    echo “Username pode conter apenas letras, números e _”;




           Alfanumérico                             Aceita _



                          @alganet

            Sem espaços                          1-15 caracteres
30 de Novembro             PHP Conference 2012                     13
if (!ctype_alnum(str_replace('_', '', $username)))
    echo “Username pode conter apenas letras, números e _”;
if (strlen($username) < 1 || strlen($username) > 15)
    echo “Username pode conter de 1 a 15 caracteres”;




           Alfanumérico                             Aceita _



                          @alganet

            Sem espaços                          1-15 caracteres
30 de Novembro             PHP Conference 2012                     14
$e = array();
if (!ctype_alnum(str_replace('_', '', $username)))
    $e[] = “Username pode conter apenas letras, números e _”;
if (strlen($username) < 1 || strlen($username) > 15)
    $e[] = “Username pode conter de 1 a 15 caracteres”;
if ($e)
    echo implode($e);



           Alfanumérico                             Aceita _



                          @alganet

            Sem espaços                          1-15 caracteres
30 de Novembro             PHP Conference 2012                     15
E o erro para o “Sem espaços”?




30 de Novembro   PHP Conference 2012   16
$e = array();
if (!ctype_alnum(str_replace('_', '', $username)))
    $e[] = “Username pode conter apenas letras, números e _”;
if (strlen($username) < 1 || strlen($username) > 15)
    $e[] = “Username pode conter de 1 a 15 caracteres”;
if (false !== strpos($username, “ ”)
    $e[] = “Username não pode conter espaços”;
/*...*/


           Alfanumérico                             Aceita _



                          @alganet

            Sem espaços                          1-15 caracteres
30 de Novembro             PHP Conference 2012                     17
Validation


30 de Novembro     PHP Conference 2012   18
Construindo um Validator
use RespectValidationRules as r;

$validator = new rAllOf(



);




 30 de Novembro       PHP Conference 2012   19
Construindo um Validator
use RespectValidationRules as r;

$validator = new rAllOf(
    new rAlnum(“_”)


);




 30 de Novembro       PHP Conference 2012   20
Construindo um Validator
use RespectValidationRules as r;

$validator = new rAllOf(
    new rAlnum(“_”),
    new rNoWhitespace

);




 30 de Novembro       PHP Conference 2012   21
Construindo um Validator
use RespectValidationRules as r;

$validator = new rAllOf(
    new rAlnum(“_”),
    new rNoWhitespace,
    new rLength(1, 15)
);




 30 de Novembro       PHP Conference 2012   22
Construindo um Validator
use RespectValidationRules as r;

$validator = new rAllOf(
    new rAlnum(“_”),
    new rNoWhitespace,
    new rLength(1, 15)
);

$isOk = $validator->validate(“alganet”);


 30 de Novembro       PHP Conference 2012   23
Tem um jeito mais simples?




30 de Novembro      PHP Conference 2012   24
Construção via Fluent Builder

use RespectValidationValidator as v;

$validator = v::alnum('_')
              ->noWhitespace()
              ->length(1, 15);

$isOk = $validator->validate(“alganet”);



 30 de Novembro     PHP Conference 2012   25
//true or false
$validator->validate($algo);




30 de Novembro   PHP Conference 2012   26
E se eu quiser coletar os erros?




30 de Novembro    PHP Conference 2012    27
try {
    $validator->check(“e ae”);
} catch (InvalidArgumentException $e) {
    echo $e->getMessage();
}




 30 de Novembro   PHP Conference 2012     28
use RespectValidationExceptions as e;
/* … */

try {
    $validator->check(“e ae”);
} catch (eAlnumException $e) {
    //faz algo
} catch (eNoWhitespaceException $e) {
    //faz algo
} catch (eLengthException $e) {
    //faz algo
}
 30 de Novembro   PHP Conference 2012     29
//Dispara exception para o primeiro
//erro
$validator->check($algo);




30 de Novembro   PHP Conference 2012   30
E se eu quiser todos os erros?




30 de Novembro     PHP Conference 2012   31
try {
    $validator->assert(“e ae”);
} catch (InvalidArgumentException $e) {
    echo $e->getFullMessage();
}




 30 de Novembro   PHP Conference 2012     32
$validator->assert(“td errado#”);


-All of the 3 required rules must pass
  |-"td errado#" must contain only letters (a-z)
  | and digits (0-9)
  |-"td errado#" must not contain whitespace
  -"td errado#" must have a length between 1
     and 15




 30 de Novembro     PHP Conference 2012        33
E se eu quiser agrupar só alguns
                  erros?




30 de Novembro   PHP Conference 2012    34
try {
    $validator->assert(“e ae”);
} catch (InvalidArgumentException $e) {
    $e->findMessages(array(
        'alnum', 'length'
    ));
}


 30 de Novembro   PHP Conference 2012     35
E se eu quiser mensagens
                    diferentes?




30 de Novembro       PHP Conference 2012   36
try {
    $validator->assert(“e ae”);
} catch (InvalidArgumentException $e) {
    $e->findMessages(array(
      'alnum' => “{{name}} Inválido”,
      'length' => “Tamanho de {{name}}
                              incorreto”
    ));
}
 30 de Novembro   PHP Conference 2012   37
//Dispara exception com todos os erros
$validator->assert($algo);




30 de Novembro   PHP Conference 2012     38
E se eu quiser validar objetos
                  inteiros?




30 de Novembro     PHP Conference 2012   39
class Tweet
{
    public $text;
    public $created_at;
    public $user;
}

class User
{
    public $name;
}

 30 de Novembro     PHP Conference 2012   40
$user = new User;
$user->name = 'alganet';

$tweet = new Tweet;
$tweet->user = $user;
$tweet->text = “http://respect.li”;
$tweet->created_at = new DateTime;



 30 de Novembro   PHP Conference 2012   41
$tweetValidator
  = v::object()
     ->instance(“Tweet”)
     ->attribute(“text”,
         v::string()->length(1, 140))
     ->attribute(“created_at”,
         v::date())
     ->attribute(“user”,
         v::object()
          ->instance(“User”)
          ->attribute(“name”,
              $usernameValidator))
    );
 30 de Novembro   PHP Conference 2012   42
$tweetValidator
  = v::object()
     ->instance(“Tweet”)
     ->attribute(“text”,
         v::string()->length(1, 140))
     ->attribute(“created_at”,
         v::date())
     ->attribute(“user”,
         v::object()
          ->instance(“User”)
          ->attribute(“name”,
              $usernameValidator))
    );
 30 de Novembro   PHP Conference 2012   43
$tweetValidator
  = v::object()
     ->instance(“Tweet”)
     ->attribute(“text”,
         v::string()->length(1, 140))
     ->attribute(“created_at”,
         v::date())
     ->attribute(“user”,
         v::object()
          ->instance(“User”)
          ->attribute(“name”,
              $usernameValidator))
    );
 30 de Novembro   PHP Conference 2012   44
$tweetValidator
  = v::object()
     ->instance(“Tweet”)
     ->attribute(“text”,
         v::string()->length(1, 140))
     ->attribute(“created_at”,
         v::date())
     ->attribute(“user”,
         v::object()
          ->instance(“User”)
          ->attribute(“name”,
              $usernameValidator))
    );
 30 de Novembro   PHP Conference 2012   45
$tweetValidator
  = v::object()
     ->instance(“Tweet”)
     ->attribute(“text”,
         v::string()->length(1, 140))
     ->attribute(“created_at”,
         v::date())
     ->attribute(“user”,
         v::object()
          ->instance(“User”)
          ->attribute(“name”,
              $usernameValidator))
    );
 30 de Novembro   PHP Conference 2012   46
//Valida atributos de objetos
 v::object()->attribute(“name”);




 //Valida chaves de array
 v::arr()->key(“email”);



30 de Novembro   PHP Conference 2012   47
//Valida atributos de objetos
 v::object()->attribute(“name”)
            //N atributos...
            ->attribute(“sex”);




 //Valida chaves de array
 v::arr()->key(“email”)
         ->key(“sex”);


30 de Novembro   PHP Conference 2012   48
//Valida atributos de objetos
 v::object()->attribute(“name”)
            //N atributos...
            ->attribute(“sex”,
                //Valida o valor também
                v::in('F', 'M'));


 //Valida chaves de array
 v::arr()->key(“email”)
         ->key(“sex”,
             v::in('F', 'M'));

30 de Novembro   PHP Conference 2012      49
E se eu quiser negar uma regra?




30 de Novembro   PHP Conference 2012   50
//Nega qualquer regra
v::not(v::string());




30 de Novembro   PHP Conference 2012   51
E as mensagens pra regras
                    negadas?




30 de Novembro       PHP Conference 2012   52
//”123” must be a string
v::string()->check(123);

//”bla bla” must not be a string
v::not(v::string())->check('bla bla');




30 de Novembro   PHP Conference 2012     53
Dá pra mudar o “123” e “bla bla”
            nas mensagens?




30 de Novembro   PHP Conference 2012   54
//Nome Completo must be a string
v::string()
 ->setName(“Nome Completo”)
 ->check(123);

//Idade must not be a string
v::not(v::string())
 ->setName(“Idade”)
 ->check('bla bla');


30 de Novembro   PHP Conference 2012   55
//Validadores Básicos de Tipo

v::arr()
v::date()
v::float()
v::int()
v::nullValue()
v::numeric()
v::object()
v::string()
v::instance()

30 de Novembro   PHP Conference 2012   56
//Validadores Básicos de Comparação

v::equals($algo)                       //   ==
v::equals($algo, true)                 //   ===
v::max($a)                             //   <
v::max($a, true)                       //   <=
v::min($a)                             //   >
v::min($a, true)                       //   >=
v::between($a, $b)                     //   >, <
v::between($a, $b, true)               //   >=, <=

30 de Novembro   PHP Conference 2012                 57
//Validadores Básicos Numéricos

v::even()
v::odd()
v::negative()
v::positive()
v::primeNumber()
v::roman() // XVI
v::multiple($algo)
v::perfectSquare($algo)

30 de Novembro   PHP Conference 2012   58
//Validadores Básicos de String

v::alnum()
v::alpha()
v::digits()
v::consonants()
v::vowels()
v::lowercase()
v::uppercase()
v::version()
v::slug() // this-is-a-slug
v::regex($exp)
30 de Novembro   PHP Conference 2012   59
//Validadores do Zend
v::zend('Hostname')->check('google.com');

//Validadores do Symfony
v::sf('Time')->check('22:30:00');




30 de Novembro   PHP Conference 2012   60
//Validadores Legais
v::arr()
 ->each(v::instance(“MeuProduto”))
 ->check($produtos);
);




30 de Novembro   PHP Conference 2012   61
//Validadores Legais

v::between(1, 15)
 ->check(7);

v::between(“yesterday”, “tomorrow”)
 ->check(new DateTime);




30 de Novembro   PHP Conference 2012   62
//Validadores Legais

v::minimumAge(18)
 ->check(“1987-07-01”);




30 de Novembro   PHP Conference 2012   63
//Validadores Legais

v::leapDate()
 ->check(“1998-02-29”);

v::leapYear()
 ->check(“1998”);




30 de Novembro   PHP Conference 2012   64
//Validadores Legais

v::contains(“bar”)
 ->check(“foo bar baz”);

v::startsWith(“foo”)
 ->check(“foo bar baz”);

v::endsWith(“baz”)
 ->check(“foo bar baz”);


30 de Novembro   PHP Conference 2012   65
//Validadores Legais

v::contains(“bar”)
 ->check(array(“foo bar baz”));

v::startsWith(“foo”)
 ->check(array(“foo bar baz”));

v::endsWith(“baz”)
 ->check(array(“foo bar baz”));


30 de Novembro   PHP Conference 2012   66
//Validadores Legais

v::oneOf(
    v::arr()->length(1, 15),
    v::object()->attribute(“items”)
);




30 de Novembro   PHP Conference 2012   67
Posso ter as minhas próprias
                    regras?




30 de Novembro     PHP Conference 2012   68
v::callback(function ($input) {
    return $input === 42;
});




30 de Novembro   PHP Conference 2012   69
Ok, mas posso ter meu próprio
                 objeto?




30 de Novembro   PHP Conference 2012   70
use RespectValidation;

class Universe
implements ValidationValidatable
extends ValidationRulesAbstractRule
{
     public function validate($input)
     {
         return $input === 42;
     }
}

v::int()->addRule(new Universe);
30 de Novembro   PHP Conference 2012    71
E as mensagens?




30 de Novembro       PHP Conference 2012   72
use RespectValidation;
class UniverseException
extends ValidationExceptionsValidationException
{
    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD
                => '{{name}} must be 42',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD
                => '{{name}} must not be 42',
        )
    );
}

30 de Novembro      PHP Conference 2012             73
Onde eu baixo?




30 de Novembro      PHP Conference 2012   74
github.com/Respect/Validation
                 Packagist
                 respect.li/pear



30 de Novembro      PHP Conference 2012    75
Perguntas?




                 github.com/Respect/Validation
                 Packagist
                 respect.li/pear



30 de Novembro      PHP Conference 2012    76
Obrigado!
                 alexandre@gaigalas.net



                    github.com/Respect/Validation
                    Packagist
                    respect.li/pear



30 de Novembro          PHP Conference 2012   77

Contenu connexe

En vedette

Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 
REST: Faça o Serviço Direito
REST: Faça o Serviço DireitoREST: Faça o Serviço Direito
REST: Faça o Serviço DireitoAlexandre Gaigalas
 
Plano de Captação de Recursos
Plano de Captação de RecursosPlano de Captação de Recursos
Plano de Captação de RecursosABCR
 
NoSQL in MySQL
NoSQL in MySQLNoSQL in MySQL
NoSQL in MySQLUlf Wendel
 
PHP para Adultos: Clean Code e Object Calisthenics
PHP para Adultos: Clean Code e Object CalisthenicsPHP para Adultos: Clean Code e Object Calisthenics
PHP para Adultos: Clean Code e Object CalisthenicsGuilherme Blanco
 
Plano de captação de recursos
Plano de captação de recursosPlano de captação de recursos
Plano de captação de recursosRodrigo Alvarez
 
Regular Expressions 101
Regular Expressions 101Regular Expressions 101
Regular Expressions 101Raj Rajandran
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 

En vedette (15)

Conceitos interfaces modernas
Conceitos interfaces modernasConceitos interfaces modernas
Conceitos interfaces modernas
 
Palestra Seguros na Importação e Exportação
Palestra Seguros na Importação e ExportaçãoPalestra Seguros na Importação e Exportação
Palestra Seguros na Importação e Exportação
 
Apresentação Share - Associação para a Partilha do Conhecimento
Apresentação  Share - Associação para a Partilha do Conhecimento Apresentação  Share - Associação para a Partilha do Conhecimento
Apresentação Share - Associação para a Partilha do Conhecimento
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
REST: Faça o Serviço Direito
REST: Faça o Serviço DireitoREST: Faça o Serviço Direito
REST: Faça o Serviço Direito
 
Plano de Captação de Recursos
Plano de Captação de RecursosPlano de Captação de Recursos
Plano de Captação de Recursos
 
NoSQL in MySQL
NoSQL in MySQLNoSQL in MySQL
NoSQL in MySQL
 
PHP para Adultos: Clean Code e Object Calisthenics
PHP para Adultos: Clean Code e Object CalisthenicsPHP para Adultos: Clean Code e Object Calisthenics
PHP para Adultos: Clean Code e Object Calisthenics
 
Javascript para adultos
Javascript para adultosJavascript para adultos
Javascript para adultos
 
Plano de captação de recursos
Plano de captação de recursosPlano de captação de recursos
Plano de captação de recursos
 
Regular Expressions 101
Regular Expressions 101Regular Expressions 101
Regular Expressions 101
 
PHP-CLI em 7 passos
PHP-CLI em 7 passosPHP-CLI em 7 passos
PHP-CLI em 7 passos
 
O esquecido do PHP
O esquecido do PHPO esquecido do PHP
O esquecido do PHP
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similaire à Domine Validação de Dados em 45min

PHP Day - PHP para iniciantes
PHP Day - PHP para iniciantesPHP Day - PHP para iniciantes
PHP Day - PHP para iniciantesAlmir Mendes
 
(Re)pensando a OOP - TDC 2012
(Re)pensando a OOP - TDC 2012(Re)pensando a OOP - TDC 2012
(Re)pensando a OOP - TDC 2012Luís Cobucci
 
Simplificando o Javascrip
Simplificando o JavascripSimplificando o Javascrip
Simplificando o JavascripMiquéias Amaro
 
PHP: Linguagem + Mysql + MVC + AJAX
PHP: Linguagem + Mysql + MVC + AJAX PHP: Linguagem + Mysql + MVC + AJAX
PHP: Linguagem + Mysql + MVC + AJAX Sérgio Souza Costa
 
Aula 02 - Introdução ao PHP - Programação Web
Aula 02  - Introdução ao PHP - Programação WebAula 02  - Introdução ao PHP - Programação Web
Aula 02 - Introdução ao PHP - Programação WebDalton Martins
 
Programando para programadores: Desafios na evolução de um Framework
Programando para programadores: Desafios na evolução de um FrameworkProgramando para programadores: Desafios na evolução de um Framework
Programando para programadores: Desafios na evolução de um FrameworkPablo Dall'Oglio
 
Adianti Framework PHPConf 2013
Adianti Framework PHPConf 2013Adianti Framework PHPConf 2013
Adianti Framework PHPConf 2013Pablo Dall'Oglio
 
Validação e Operações CRUD em PHP
Validação e Operações CRUD em PHPValidação e Operações CRUD em PHP
Validação e Operações CRUD em PHPBreno Vitorino
 
Mini Curso PHP Twig - PHP Conference 2017
Mini Curso PHP Twig - PHP Conference 2017 Mini Curso PHP Twig - PHP Conference 2017
Mini Curso PHP Twig - PHP Conference 2017 Luis Gustavo Almeida
 
Groovy para javeiros - Migração Painless
Groovy para javeiros - Migração PainlessGroovy para javeiros - Migração Painless
Groovy para javeiros - Migração PainlessRafael Farias Silva
 
Prog web 02-php-primeiros-passos
Prog web 02-php-primeiros-passosProg web 02-php-primeiros-passos
Prog web 02-php-primeiros-passosRegis Magalhães
 
User Interface (in portuguese)
User Interface (in portuguese)User Interface (in portuguese)
User Interface (in portuguese)Bruno Pedro
 
J query javascript para seres humanos
J query   javascript para seres humanosJ query   javascript para seres humanos
J query javascript para seres humanosnobios
 
LabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveis
LabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveisLabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveis
LabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveisCarlos Santos
 

Similaire à Domine Validação de Dados em 45min (20)

PHP GERAL
PHP GERALPHP GERAL
PHP GERAL
 
PHP Day - PHP para iniciantes
PHP Day - PHP para iniciantesPHP Day - PHP para iniciantes
PHP Day - PHP para iniciantes
 
(Re)pensando a OOP - TDC 2012
(Re)pensando a OOP - TDC 2012(Re)pensando a OOP - TDC 2012
(Re)pensando a OOP - TDC 2012
 
Simplificando o Javascrip
Simplificando o JavascripSimplificando o Javascrip
Simplificando o Javascrip
 
PHP: Linguagem + Mysql + MVC + AJAX
PHP: Linguagem + Mysql + MVC + AJAX PHP: Linguagem + Mysql + MVC + AJAX
PHP: Linguagem + Mysql + MVC + AJAX
 
Aula 02 - Introdução ao PHP - Programação Web
Aula 02  - Introdução ao PHP - Programação WebAula 02  - Introdução ao PHP - Programação Web
Aula 02 - Introdução ao PHP - Programação Web
 
M5 php rc
M5 php rcM5 php rc
M5 php rc
 
Programando para programadores: Desafios na evolução de um Framework
Programando para programadores: Desafios na evolução de um FrameworkProgramando para programadores: Desafios na evolução de um Framework
Programando para programadores: Desafios na evolução de um Framework
 
Aula 01 - Curso PHP e MySQL
Aula 01 - Curso PHP e MySQLAula 01 - Curso PHP e MySQL
Aula 01 - Curso PHP e MySQL
 
Adianti Framework PHPConf 2013
Adianti Framework PHPConf 2013Adianti Framework PHPConf 2013
Adianti Framework PHPConf 2013
 
Validação e Operações CRUD em PHP
Validação e Operações CRUD em PHPValidação e Operações CRUD em PHP
Validação e Operações CRUD em PHP
 
Mini Curso PHP Twig - PHP Conference 2017
Mini Curso PHP Twig - PHP Conference 2017 Mini Curso PHP Twig - PHP Conference 2017
Mini Curso PHP Twig - PHP Conference 2017
 
Groovy para javeiros - Migração Painless
Groovy para javeiros - Migração PainlessGroovy para javeiros - Migração Painless
Groovy para javeiros - Migração Painless
 
Revisao php
Revisao phpRevisao php
Revisao php
 
Prog web 02-php-primeiros-passos
Prog web 02-php-primeiros-passosProg web 02-php-primeiros-passos
Prog web 02-php-primeiros-passos
 
Php 02 Primeiros Passos
Php 02 Primeiros PassosPhp 02 Primeiros Passos
Php 02 Primeiros Passos
 
User Interface (in portuguese)
User Interface (in portuguese)User Interface (in portuguese)
User Interface (in portuguese)
 
Introdução a php
Introdução a phpIntrodução a php
Introdução a php
 
J query javascript para seres humanos
J query   javascript para seres humanosJ query   javascript para seres humanos
J query javascript para seres humanos
 
LabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveis
LabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveisLabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveis
LabMM4 (T11 - 12/13) - PHP - Tipos de dados e variáveis
 

Plus de Alexandre Gaigalas

REST: Faça o Serviço Direito - TDC Goiânia
REST: Faça o Serviço Direito - TDC GoiâniaREST: Faça o Serviço Direito - TDC Goiânia
REST: Faça o Serviço Direito - TDC GoiâniaAlexandre Gaigalas
 
Mágica com Manipulação de Imagens - TDC 2011 Goiânia
Mágica com Manipulação de Imagens - TDC 2011 GoiâniaMágica com Manipulação de Imagens - TDC 2011 Goiânia
Mágica com Manipulação de Imagens - TDC 2011 GoiâniaAlexandre Gaigalas
 
assertTrue($tdd) - Latinoware 2011
assertTrue($tdd) - Latinoware 2011assertTrue($tdd) - Latinoware 2011
assertTrue($tdd) - Latinoware 2011Alexandre Gaigalas
 
REST: Faça o Serviço Direito
REST: Faça o Serviço DireitoREST: Faça o Serviço Direito
REST: Faça o Serviço DireitoAlexandre Gaigalas
 
Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011
Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011
Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011Alexandre Gaigalas
 
HTTP: A Base do Desenvolvimento Web - FISL 12
HTTP: A Base do Desenvolvimento Web - FISL 12HTTP: A Base do Desenvolvimento Web - FISL 12
HTTP: A Base do Desenvolvimento Web - FISL 12Alexandre Gaigalas
 
Varrendo APIs REST em Larga Escala utilizando PHP
Varrendo APIs REST em Larga Escala utilizando PHPVarrendo APIs REST em Larga Escala utilizando PHP
Varrendo APIs REST em Larga Escala utilizando PHPAlexandre Gaigalas
 

Plus de Alexandre Gaigalas (11)

As Mudanças Culturais do PHP
As Mudanças Culturais do PHPAs Mudanças Culturais do PHP
As Mudanças Culturais do PHP
 
PHP Maroto
PHP MarotoPHP Maroto
PHP Maroto
 
REST: Faça o Serviço Direito - TDC Goiânia
REST: Faça o Serviço Direito - TDC GoiâniaREST: Faça o Serviço Direito - TDC Goiânia
REST: Faça o Serviço Direito - TDC Goiânia
 
Mágica com Manipulação de Imagens - TDC 2011 Goiânia
Mágica com Manipulação de Imagens - TDC 2011 GoiâniaMágica com Manipulação de Imagens - TDC 2011 Goiânia
Mágica com Manipulação de Imagens - TDC 2011 Goiânia
 
assertTrue($tdd) - Latinoware 2011
assertTrue($tdd) - Latinoware 2011assertTrue($tdd) - Latinoware 2011
assertTrue($tdd) - Latinoware 2011
 
REST: Faça o Serviço Direito
REST: Faça o Serviço DireitoREST: Faça o Serviço Direito
REST: Faça o Serviço Direito
 
Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011
Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011
Autoloaders Universais + Microframeworks em PHP - Trilha de PHP do TDC 2011
 
HTTP: A Base do Desenvolvimento Web - FISL 12
HTTP: A Base do Desenvolvimento Web - FISL 12HTTP: A Base do Desenvolvimento Web - FISL 12
HTTP: A Base do Desenvolvimento Web - FISL 12
 
GET /conceitos HTTP/1.1
GET /conceitos HTTP/1.1GET /conceitos HTTP/1.1
GET /conceitos HTTP/1.1
 
assertTrue($tdd)
assertTrue($tdd)assertTrue($tdd)
assertTrue($tdd)
 
Varrendo APIs REST em Larga Escala utilizando PHP
Varrendo APIs REST em Larga Escala utilizando PHPVarrendo APIs REST em Larga Escala utilizando PHP
Varrendo APIs REST em Larga Escala utilizando PHP
 

Dernier

Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsDanilo Pinotti
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx2m Assessoria
 
Programação Orientada a Objetos - 4 Pilares.pdf
Programação Orientada a Objetos - 4 Pilares.pdfProgramação Orientada a Objetos - 4 Pilares.pdf
Programação Orientada a Objetos - 4 Pilares.pdfSamaraLunas
 
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx2m Assessoria
 
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx2m Assessoria
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploDanilo Pinotti
 
Luís Kitota AWS Discovery Day Ka Solution.pdf
Luís Kitota AWS Discovery Day Ka Solution.pdfLuís Kitota AWS Discovery Day Ka Solution.pdf
Luís Kitota AWS Discovery Day Ka Solution.pdfLuisKitota
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx2m Assessoria
 

Dernier (8)

Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object Calisthenics
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
 
Programação Orientada a Objetos - 4 Pilares.pdf
Programação Orientada a Objetos - 4 Pilares.pdfProgramação Orientada a Objetos - 4 Pilares.pdf
Programação Orientada a Objetos - 4 Pilares.pdf
 
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
 
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemplo
 
Luís Kitota AWS Discovery Day Ka Solution.pdf
Luís Kitota AWS Discovery Day Ka Solution.pdfLuís Kitota AWS Discovery Day Ka Solution.pdf
Luís Kitota AWS Discovery Day Ka Solution.pdf
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
 

Domine Validação de Dados em 45min

  • 1. Domine Validação de Dados em 45min 30 de Novembro PHP Conference 2012 1
  • 2. Alexandre Gaigalas http://about.me/alganet 30 de Novembro PHP Conference 2012 2
  • 3. @alganet 30 de Novembro PHP Conference 2012 3
  • 4. Alfanumérico @alganet 30 de Novembro PHP Conference 2012 4
  • 5. Alfanumérico Aceita _ @alganet 30 de Novembro PHP Conference 2012 5
  • 6. Alfanumérico Aceita _ @alganet Sem espaços 30 de Novembro PHP Conference 2012 6
  • 7. Alfanumérico Aceita _ @alganet Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 7
  • 8. /^[[:alnum:]_]{1,15}$/ (Expressão Regular) Alfanumérico Aceita _ @alganet Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 8
  • 9. /^[[:alnum:]_]{1,15}$/ Alfanumérico Aceita _ @alexandre_gomes_gaigalas Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 9
  • 10. /^[[:alnum:]_]{1,15}$/ Alfanumérico Aceita _ @al-ga-net Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 10
  • 11. /^[[:alnum:]_]{1,15}$/ Alfanumérico Aceita _ @Alexandre Gomes Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 11
  • 12. E se eu quiser exibir os erros? 30 de Novembro PHP Conference 2012 12
  • 13. if (!ctype_alnum(str_replace('_', '', $username))) echo “Username pode conter apenas letras, números e _”; Alfanumérico Aceita _ @alganet Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 13
  • 14. if (!ctype_alnum(str_replace('_', '', $username))) echo “Username pode conter apenas letras, números e _”; if (strlen($username) < 1 || strlen($username) > 15) echo “Username pode conter de 1 a 15 caracteres”; Alfanumérico Aceita _ @alganet Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 14
  • 15. $e = array(); if (!ctype_alnum(str_replace('_', '', $username))) $e[] = “Username pode conter apenas letras, números e _”; if (strlen($username) < 1 || strlen($username) > 15) $e[] = “Username pode conter de 1 a 15 caracteres”; if ($e) echo implode($e); Alfanumérico Aceita _ @alganet Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 15
  • 16. E o erro para o “Sem espaços”? 30 de Novembro PHP Conference 2012 16
  • 17. $e = array(); if (!ctype_alnum(str_replace('_', '', $username))) $e[] = “Username pode conter apenas letras, números e _”; if (strlen($username) < 1 || strlen($username) > 15) $e[] = “Username pode conter de 1 a 15 caracteres”; if (false !== strpos($username, “ ”) $e[] = “Username não pode conter espaços”; /*...*/ Alfanumérico Aceita _ @alganet Sem espaços 1-15 caracteres 30 de Novembro PHP Conference 2012 17
  • 18. Validation 30 de Novembro PHP Conference 2012 18
  • 19. Construindo um Validator use RespectValidationRules as r; $validator = new rAllOf( ); 30 de Novembro PHP Conference 2012 19
  • 20. Construindo um Validator use RespectValidationRules as r; $validator = new rAllOf( new rAlnum(“_”) ); 30 de Novembro PHP Conference 2012 20
  • 21. Construindo um Validator use RespectValidationRules as r; $validator = new rAllOf( new rAlnum(“_”), new rNoWhitespace ); 30 de Novembro PHP Conference 2012 21
  • 22. Construindo um Validator use RespectValidationRules as r; $validator = new rAllOf( new rAlnum(“_”), new rNoWhitespace, new rLength(1, 15) ); 30 de Novembro PHP Conference 2012 22
  • 23. Construindo um Validator use RespectValidationRules as r; $validator = new rAllOf( new rAlnum(“_”), new rNoWhitespace, new rLength(1, 15) ); $isOk = $validator->validate(“alganet”); 30 de Novembro PHP Conference 2012 23
  • 24. Tem um jeito mais simples? 30 de Novembro PHP Conference 2012 24
  • 25. Construção via Fluent Builder use RespectValidationValidator as v; $validator = v::alnum('_') ->noWhitespace() ->length(1, 15); $isOk = $validator->validate(“alganet”); 30 de Novembro PHP Conference 2012 25
  • 26. //true or false $validator->validate($algo); 30 de Novembro PHP Conference 2012 26
  • 27. E se eu quiser coletar os erros? 30 de Novembro PHP Conference 2012 27
  • 28. try { $validator->check(“e ae”); } catch (InvalidArgumentException $e) { echo $e->getMessage(); } 30 de Novembro PHP Conference 2012 28
  • 29. use RespectValidationExceptions as e; /* … */ try { $validator->check(“e ae”); } catch (eAlnumException $e) { //faz algo } catch (eNoWhitespaceException $e) { //faz algo } catch (eLengthException $e) { //faz algo } 30 de Novembro PHP Conference 2012 29
  • 30. //Dispara exception para o primeiro //erro $validator->check($algo); 30 de Novembro PHP Conference 2012 30
  • 31. E se eu quiser todos os erros? 30 de Novembro PHP Conference 2012 31
  • 32. try { $validator->assert(“e ae”); } catch (InvalidArgumentException $e) { echo $e->getFullMessage(); } 30 de Novembro PHP Conference 2012 32
  • 33. $validator->assert(“td errado#”); -All of the 3 required rules must pass |-"td errado#" must contain only letters (a-z) | and digits (0-9) |-"td errado#" must not contain whitespace -"td errado#" must have a length between 1 and 15 30 de Novembro PHP Conference 2012 33
  • 34. E se eu quiser agrupar só alguns erros? 30 de Novembro PHP Conference 2012 34
  • 35. try { $validator->assert(“e ae”); } catch (InvalidArgumentException $e) { $e->findMessages(array( 'alnum', 'length' )); } 30 de Novembro PHP Conference 2012 35
  • 36. E se eu quiser mensagens diferentes? 30 de Novembro PHP Conference 2012 36
  • 37. try { $validator->assert(“e ae”); } catch (InvalidArgumentException $e) { $e->findMessages(array( 'alnum' => “{{name}} Inválido”, 'length' => “Tamanho de {{name}} incorreto” )); } 30 de Novembro PHP Conference 2012 37
  • 38. //Dispara exception com todos os erros $validator->assert($algo); 30 de Novembro PHP Conference 2012 38
  • 39. E se eu quiser validar objetos inteiros? 30 de Novembro PHP Conference 2012 39
  • 40. class Tweet { public $text; public $created_at; public $user; } class User { public $name; } 30 de Novembro PHP Conference 2012 40
  • 41. $user = new User; $user->name = 'alganet'; $tweet = new Tweet; $tweet->user = $user; $tweet->text = “http://respect.li”; $tweet->created_at = new DateTime; 30 de Novembro PHP Conference 2012 41
  • 42. $tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) ); 30 de Novembro PHP Conference 2012 42
  • 43. $tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) ); 30 de Novembro PHP Conference 2012 43
  • 44. $tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) ); 30 de Novembro PHP Conference 2012 44
  • 45. $tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) ); 30 de Novembro PHP Conference 2012 45
  • 46. $tweetValidator = v::object() ->instance(“Tweet”) ->attribute(“text”, v::string()->length(1, 140)) ->attribute(“created_at”, v::date()) ->attribute(“user”, v::object() ->instance(“User”) ->attribute(“name”, $usernameValidator)) ); 30 de Novembro PHP Conference 2012 46
  • 47. //Valida atributos de objetos v::object()->attribute(“name”); //Valida chaves de array v::arr()->key(“email”); 30 de Novembro PHP Conference 2012 47
  • 48. //Valida atributos de objetos v::object()->attribute(“name”) //N atributos... ->attribute(“sex”); //Valida chaves de array v::arr()->key(“email”) ->key(“sex”); 30 de Novembro PHP Conference 2012 48
  • 49. //Valida atributos de objetos v::object()->attribute(“name”) //N atributos... ->attribute(“sex”, //Valida o valor também v::in('F', 'M')); //Valida chaves de array v::arr()->key(“email”) ->key(“sex”, v::in('F', 'M')); 30 de Novembro PHP Conference 2012 49
  • 50. E se eu quiser negar uma regra? 30 de Novembro PHP Conference 2012 50
  • 51. //Nega qualquer regra v::not(v::string()); 30 de Novembro PHP Conference 2012 51
  • 52. E as mensagens pra regras negadas? 30 de Novembro PHP Conference 2012 52
  • 53. //”123” must be a string v::string()->check(123); //”bla bla” must not be a string v::not(v::string())->check('bla bla'); 30 de Novembro PHP Conference 2012 53
  • 54. Dá pra mudar o “123” e “bla bla” nas mensagens? 30 de Novembro PHP Conference 2012 54
  • 55. //Nome Completo must be a string v::string() ->setName(“Nome Completo”) ->check(123); //Idade must not be a string v::not(v::string()) ->setName(“Idade”) ->check('bla bla'); 30 de Novembro PHP Conference 2012 55
  • 56. //Validadores Básicos de Tipo v::arr() v::date() v::float() v::int() v::nullValue() v::numeric() v::object() v::string() v::instance() 30 de Novembro PHP Conference 2012 56
  • 57. //Validadores Básicos de Comparação v::equals($algo) // == v::equals($algo, true) // === v::max($a) // < v::max($a, true) // <= v::min($a) // > v::min($a, true) // >= v::between($a, $b) // >, < v::between($a, $b, true) // >=, <= 30 de Novembro PHP Conference 2012 57
  • 58. //Validadores Básicos Numéricos v::even() v::odd() v::negative() v::positive() v::primeNumber() v::roman() // XVI v::multiple($algo) v::perfectSquare($algo) 30 de Novembro PHP Conference 2012 58
  • 59. //Validadores Básicos de String v::alnum() v::alpha() v::digits() v::consonants() v::vowels() v::lowercase() v::uppercase() v::version() v::slug() // this-is-a-slug v::regex($exp) 30 de Novembro PHP Conference 2012 59
  • 60. //Validadores do Zend v::zend('Hostname')->check('google.com'); //Validadores do Symfony v::sf('Time')->check('22:30:00'); 30 de Novembro PHP Conference 2012 60
  • 61. //Validadores Legais v::arr() ->each(v::instance(“MeuProduto”)) ->check($produtos); ); 30 de Novembro PHP Conference 2012 61
  • 62. //Validadores Legais v::between(1, 15) ->check(7); v::between(“yesterday”, “tomorrow”) ->check(new DateTime); 30 de Novembro PHP Conference 2012 62
  • 64. //Validadores Legais v::leapDate() ->check(“1998-02-29”); v::leapYear() ->check(“1998”); 30 de Novembro PHP Conference 2012 64
  • 65. //Validadores Legais v::contains(“bar”) ->check(“foo bar baz”); v::startsWith(“foo”) ->check(“foo bar baz”); v::endsWith(“baz”) ->check(“foo bar baz”); 30 de Novembro PHP Conference 2012 65
  • 66. //Validadores Legais v::contains(“bar”) ->check(array(“foo bar baz”)); v::startsWith(“foo”) ->check(array(“foo bar baz”)); v::endsWith(“baz”) ->check(array(“foo bar baz”)); 30 de Novembro PHP Conference 2012 66
  • 67. //Validadores Legais v::oneOf( v::arr()->length(1, 15), v::object()->attribute(“items”) ); 30 de Novembro PHP Conference 2012 67
  • 68. Posso ter as minhas próprias regras? 30 de Novembro PHP Conference 2012 68
  • 69. v::callback(function ($input) { return $input === 42; }); 30 de Novembro PHP Conference 2012 69
  • 70. Ok, mas posso ter meu próprio objeto? 30 de Novembro PHP Conference 2012 70
  • 71. use RespectValidation; class Universe implements ValidationValidatable extends ValidationRulesAbstractRule { public function validate($input) { return $input === 42; } } v::int()->addRule(new Universe); 30 de Novembro PHP Conference 2012 71
  • 72. E as mensagens? 30 de Novembro PHP Conference 2012 72
  • 73. use RespectValidation; class UniverseException extends ValidationExceptionsValidationException { public static $defaultTemplates = array( self::MODE_DEFAULT => array( self::STANDARD => '{{name}} must be 42', ), self::MODE_NEGATIVE => array( self::STANDARD => '{{name}} must not be 42', ) ); } 30 de Novembro PHP Conference 2012 73
  • 74. Onde eu baixo? 30 de Novembro PHP Conference 2012 74
  • 75. github.com/Respect/Validation Packagist respect.li/pear 30 de Novembro PHP Conference 2012 75
  • 76. Perguntas? github.com/Respect/Validation Packagist respect.li/pear 30 de Novembro PHP Conference 2012 76
  • 77. Obrigado! alexandre@gaigalas.net github.com/Respect/Validation Packagist respect.li/pear 30 de Novembro PHP Conference 2012 77