Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Domine Validação de Dados em 45min

Domine Validação de Dados em 45min

Alexandre Gaigalas

March 11, 2013

Transcript

77 slides
  1. 30 de Novembro PHP Conference 2012 8 @alganet Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços /^[[:alnum:]_]{1,15}$/ (Expressão Regular)
  2. 30 de Novembro PHP Conference 2012 9 @alexandre_gomes_gaigalas Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços /^[[:alnum:]_]{1,15}$/
  3. 30 de Novembro PHP Conference 2012 10 @al-ga-net Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços /^[[:alnum:]_]{1,15}$/
  4. 30 de Novembro PHP Conference 2012 11 @Alexandre Gomes Alfanumérico

    Aceita _ 1-15 caracteres Sem espaços /^[[:alnum:]_]{1,15}$/
  5. 30 de Novembro PHP Conference 2012 13 @alganet Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços if (!ctype_alnum(str_replace('_', '', $username))) echo “Username pode conter apenas letras, números e _”;
  6. 30 de Novembro PHP Conference 2012 14 @alganet Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços 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”;
  7. 30 de Novembro PHP Conference 2012 15 @alganet Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços $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);
  8. 30 de Novembro PHP Conference 2012 17 @alganet Alfanumérico Aceita

    _ 1-15 caracteres Sem espaços $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”; /*...*/
  9. 30 de Novembro PHP Conference 2012 19 use Respect\Validation\Rules as

    r; $validator = new r\AllOf( ); Construindo um Validator
  10. 30 de Novembro PHP Conference 2012 20 use Respect\Validation\Rules as

    r; $validator = new r\AllOf( new r\Alnum(“_”) ); Construindo um Validator
  11. 30 de Novembro PHP Conference 2012 21 use Respect\Validation\Rules as

    r; $validator = new r\AllOf( new r\Alnum(“_”), new r\NoWhitespace ); Construindo um Validator
  12. 30 de Novembro PHP Conference 2012 22 use Respect\Validation\Rules as

    r; $validator = new r\AllOf( new r\Alnum(“_”), new r\NoWhitespace, new r\Length(1, 15) ); Construindo um Validator
  13. 30 de Novembro PHP Conference 2012 23 use Respect\Validation\Rules as

    r; $validator = new r\AllOf( new r\Alnum(“_”), new r\NoWhitespace, new r\Length(1, 15) ); $isOk = $validator->validate(“alganet”); Construindo um Validator
  14. 30 de Novembro PHP Conference 2012 25 use Respect\Validation\Validator as

    v; $validator = v::alnum('_') ->noWhitespace() ->length(1, 15); $isOk = $validator->validate(“alganet”); Construção via Fluent Builder
  15. 30 de Novembro PHP Conference 2012 28 try { $validator->check(“e

    ae”); } catch (InvalidArgumentException $e) { echo $e->getMessage(); }
  16. 30 de Novembro PHP Conference 2012 29 use Respect\Validation\Exceptions as

    e; /* … */ try { $validator->check(“e ae”); } catch (e\AlnumException $e) { //faz algo } catch (e\NoWhitespaceException $e) { //faz algo } catch (e\LengthException $e) { //faz algo }
  17. 30 de Novembro PHP Conference 2012 30 //Dispara exception para

    o primeiro //erro $validator->check($algo);
  18. 30 de Novembro PHP Conference 2012 32 try { $validator->assert(“e

    ae”); } catch (InvalidArgumentException $e) { echo $e->getFullMessage(); }
  19. 30 de Novembro PHP Conference 2012 33 \-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 $validator->assert(“td errado#”);
  20. 30 de Novembro PHP Conference 2012 34 E se eu

    quiser agrupar só alguns erros?
  21. 30 de Novembro PHP Conference 2012 35 try { $validator->assert(“e

    ae”); } catch (InvalidArgumentException $e) { $e->findMessages(array( 'alnum', 'length' )); }
  22. 30 de Novembro PHP Conference 2012 36 E se eu

    quiser mensagens diferentes?
  23. 30 de Novembro PHP Conference 2012 37 try { $validator->assert(“e

    ae”); } catch (InvalidArgumentException $e) { $e->findMessages(array( 'alnum' => “{{name}} Inválido”, 'length' => “Tamanho de {{name}} incorreto” )); }
  24. 30 de Novembro PHP Conference 2012 38 //Dispara exception com

    todos os erros $validator->assert($algo);
  25. 30 de Novembro PHP Conference 2012 39 E se eu

    quiser validar objetos inteiros?
  26. 30 de Novembro PHP Conference 2012 40 class Tweet {

    public $text; public $created_at; public $user; } class User { public $name; }
  27. 30 de Novembro PHP Conference 2012 41 $user = new

    User; $user->name = 'alganet'; $tweet = new Tweet; $tweet->user = $user; $tweet->text = “http://respect.li”; $tweet->created_at = new DateTime;
  28. 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)) );
  29. 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. 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)) );
  31. 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)) );
  32. 30 de Novembro PHP Conference 2012 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)) );
  33. 30 de Novembro PHP Conference 2012 47 //Valida atributos de

    objetos v::object()->attribute(“name”); //Valida chaves de array v::arr()->key(“email”);
  34. 30 de Novembro PHP Conference 2012 48 //Valida atributos de

    objetos v::object()->attribute(“name”) //N atributos... ->attribute(“sex”); //Valida chaves de array v::arr()->key(“email”) ->key(“sex”);
  35. 30 de Novembro PHP Conference 2012 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'));
  36. 30 de Novembro PHP Conference 2012 53 //”123” must be

    a string v::string()->check(123); //”bla bla” must not be a string v::not(v::string())->check('bla bla');
  37. 30 de Novembro PHP Conference 2012 54 Dá pra mudar

    o “123” e “bla bla” nas mensagens?
  38. 30 de Novembro PHP Conference 2012 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');
  39. 30 de Novembro PHP Conference 2012 56 //Validadores Básicos de

    Tipo v::arr() v::date() v::float() v::int() v::nullValue() v::numeric() v::object() v::string() v::instance()
  40. 30 de Novembro PHP Conference 2012 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) // >=, <=
  41. 30 de Novembro PHP Conference 2012 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)
  42. 30 de Novembro PHP Conference 2012 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)
  43. 30 de Novembro PHP Conference 2012 60 //Validadores do Zend

    v::zend('Hostname')->check('google.com'); //Validadores do Symfony v::sf('Time')->check('22:30:00');
  44. 30 de Novembro PHP Conference 2012 61 //Validadores Legais v::arr()

    ->each(v::instance(“MeuProduto”)) ->check($produtos); );
  45. 30 de Novembro PHP Conference 2012 62 //Validadores Legais v::between(1,

    15) ->check(7); v::between(“yesterday”, “tomorrow”) ->check(new DateTime);
  46. 30 de Novembro PHP Conference 2012 64 //Validadores Legais v::leapDate()

    ->check(“1998-02-29”); v::leapYear() ->check(“1998”);
  47. 30 de Novembro PHP Conference 2012 65 //Validadores Legais v::contains(“bar”)

    ->check(“foo bar baz”); v::startsWith(“foo”) ->check(“foo bar baz”); v::endsWith(“baz”) ->check(“foo bar baz”);
  48. 30 de Novembro PHP Conference 2012 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”));
  49. 30 de Novembro PHP Conference 2012 67 //Validadores Legais v::oneOf(

    v::arr()->length(1, 15), v::object()->attribute(“items”) );
  50. 30 de Novembro PHP Conference 2012 71 use Respect\Validation; class

    Universe implements Validation\Validatable extends Validation\Rules\AbstractRule { public function validate($input) { return $input === 42; } } v::int()->addRule(new Universe);
  51. 30 de Novembro PHP Conference 2012 73 use Respect\Validation; class

    UniverseException extends Validation\Exceptions\ValidationException { 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', ) ); }

More Decks by Alexandre Gaigalas

Other Decks in Technology