PageRenderTime 63ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/README.md

http://github.com/Respect/Validation
Markdown | 310 lines | 228 code | 82 blank | 0 comment | 0 complexity | da02007b67a16f5a1626eb4c5eab492e MD5 | raw file
Possible License(s): MIT, BSD-3-Clause
  1. # Feature Guide
  2. ## Namespace import
  3. Respect\Validation is namespaced, but you can make your life easier by importing
  4. a single class into your context:
  5. ```php
  6. use Respect\Validation\Validator as v;
  7. ```
  8. ## Simple validation
  9. The Hello World validator is something like this:
  10. ```php
  11. $number = 123;
  12. v::numeric()->validate($number); // true
  13. ```
  14. ## Chained validation
  15. It is possible to use validators in a chain. Sample below validates a string
  16. containing numbers and letters, no whitespace and length between 1 and 15.
  17. ```php
  18. $usernameValidator = v::alnum()->noWhitespace()->length(1, 15);
  19. $usernameValidator->validate('alganet'); // true
  20. ```
  21. ## Validating object attributes
  22. Given this simple object:
  23. ```php
  24. $user = new stdClass;
  25. $user->name = 'Alexandre';
  26. $user->birthdate = '1987-07-01';
  27. ```
  28. Is possible to validate its attributes in a single chain:
  29. ```php
  30. $userValidator = v::attribute('name', v::stringType()->length(1,32))
  31. ->attribute('birthdate', v::date()->age(18));
  32. $userValidator->validate($user); // true
  33. ```
  34. Validating array keys is also possible using `v::key()`
  35. Note that we used `v::stringType()` and `v::date()` in the beginning of the validator.
  36. Although is not mandatory, it is a good practice to use the type of the
  37. validated object as the first node in the chain.
  38. ## Input optional
  39. On oldest versions of Respect\Validation all validators treat input as optional
  40. and accept an empty string input as valid. Even though a useful feature that
  41. caused a lot of troubles for our team and neither was an obvious behavior. Also
  42. there was some people who likes to accept `null` as optional value, not only an
  43. empty string.
  44. For that reason all rules are mandatory now but if you want to treat a value as
  45. optional you can use `v::optional()` rule:
  46. ```php
  47. v::alpha()->validate(''); // false input required
  48. v::alpha()->validate(null); // false input required
  49. v::optional(v::alpha())->validate(''); // true
  50. v::optional(v::alpha())->validate(null); // true
  51. ```
  52. By _optional_ we consider `null` or an empty string (`''`).
  53. See more on [Optional](Optional.md).
  54. ## Negating rules
  55. You can use the `v::not()` to negate any rule:
  56. ```php
  57. v::not(v::intVal())->validate(10); // false, input must not be integer
  58. ```
  59. ## Validator reuse
  60. Once created, you can reuse your validator anywhere. Remember `$usernameValidator`?
  61. ```php
  62. $usernameValidator->validate('respect'); //true
  63. $usernameValidator->validate('alexandre gaigalas'); // false
  64. $usernameValidator->validate('#$%'); //false
  65. ```
  66. ## Exception types
  67. * `Respect\Validation\Exceptions\ExceptionInterface`:
  68. * All exceptions implement this interface;
  69. * `Respect\Validation\Exceptions\ValidationException`:
  70. * Implements the `Respect\Validation\Exceptions\ExceptionInterface` interface
  71. * Thrown when the `check()` fails
  72. * All validation exceptions extend this class
  73. * Available methods:
  74. * `getMainMessage()`;
  75. * `setMode($mode)`;
  76. * `setName($name)`;
  77. * `setParam($name, $value)`;
  78. * `setTemplate($template)`;
  79. * more...
  80. * `Respect\Validation\Exceptions\NestedValidationException`:
  81. * Extends the `Respect\Validation\Exceptions\ValidationException` class
  82. * Usually thrown when the `assert()` fails
  83. * Available methods:
  84. * `findMessages()`;
  85. * `getFullMessage()`;
  86. * `getMessages()`;
  87. * more...
  88. ## Informative exceptions
  89. When something goes wrong, Validation can tell you exactly what's going on. For this,
  90. we use the `assert()` method instead of `validate()`:
  91. ```php
  92. use Respect\Validation\Exceptions\NestedValidationException;
  93. try {
  94. $usernameValidator->assert('really messed up screen#name');
  95. } catch(NestedValidationException $exception) {
  96. echo $exception->getFullMessage();
  97. }
  98. ```
  99. The printed message is exactly this, as a nested Markdown list:
  100. ```no-highlight
  101. - All of the required rules must pass for "really messed up screen#name"
  102. - "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
  103. - "really messed up screen#name" must not contain whitespace
  104. - "really messed up screen#name" must have a length between 1 and 15
  105. ```
  106. ## Getting all messages as an array
  107. The Markdown list is fine, but unusable on a HTML form or something more custom.
  108. For that you can use `getMessages()`.
  109. It will return all messages from the rules that did not pass the validation.
  110. ```php
  111. try {
  112. $usernameValidator->assert('really messed up screen#name');
  113. } catch(NestedValidationException $exception) {
  114. print_r($exception->getMessages());
  115. }
  116. ```
  117. The code above may display something like:
  118. ```no-highlight
  119. Array
  120. (
  121. [0] => "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
  122. [1] => "really messed up screen#name" must not contain whitespace
  123. [2] => "really messed up screen#name" must have a length between 1 and 15
  124. )
  125. ```
  126. ## Getting messages as an array by name
  127. If you want to get specific message by name you can use `findMessages()` passing
  128. the names of the rules you want:
  129. ```php
  130. try {
  131. $usernameValidator->assert('really messed up screen#name');
  132. } catch(NestedValidationException $exception) {
  133. print_r($exception->findMessages(['alnum', 'noWhitespace']));
  134. }
  135. ```
  136. The `findMessages()` returns an array with messages from the requested validators,
  137. like this:
  138. ```no-highlight
  139. Array
  140. (
  141. [alnum] => "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
  142. [noWhitespace] => "really messed up screen#name" must not contain whitespace
  143. )
  144. ```
  145. ## Custom messages
  146. Getting messages as an array is fine, but sometimes you need to customize them in order
  147. to present them to the user. This is possible using the `findMessages()` method as well:
  148. ```php
  149. $errors = $exception->findMessages([
  150. 'alnum' => '{{name}} must contain only letters and digits',
  151. 'length' => '{{name}} must not have more than 15 chars',
  152. 'noWhitespace' => '{{name}} cannot contain spaces'
  153. ]);
  154. ```
  155. For all messages, the `{{name}}` variable is available for templates. If you
  156. do not define a name it uses the input to replace this placeholder.
  157. ## Message localization
  158. You're also able to translate your message to another language with Validation.
  159. The only thing one must do is to define the param `translator` as a callable that
  160. will handle the translation:
  161. ```php
  162. $exception->setParam('translator', 'gettext');
  163. ```
  164. The example above uses `gettext()` but you can use any other callable value, like
  165. `[$translator, 'trans']` or `you_custom_function()`.
  166. After that, if you call `getMainMessage()` or `getFullMessage()` (for nested),
  167. the message will be translated.
  168. Note that `getMessage()` will keep the original message.
  169. ## Custom rules
  170. You also can use your own rules:
  171. ```php
  172. namespace My\Validation\Rules;
  173. use Respect\Validation\Rules\AbstractRule;
  174. class MyRule extends AbstractRule
  175. {
  176. public function validate($input)
  177. {
  178. // Do something here with the $input and return a boolean value
  179. }
  180. }
  181. ```
  182. If you do want Validation to execute you rule (or rules) in the chain, you must
  183. use `v::with()` passing your rule's namespace as an argument:
  184. ```php
  185. v::with('My\\Validation\\Rules\\');
  186. v::myRule(); // Try to load "My\Validation\Rules\MyRule" if any
  187. ```
  188. By default `with()` appends the given prefix, but you can change this behavior
  189. in order to overwrite default rules:
  190. ```php
  191. v::with('My\\Validation\\Rules', true);
  192. v::alnum(); // Try to use "My\Validation\Rules\Alnum" if any
  193. ```
  194. ## Validator name
  195. On `v::attribute()` and `v::key()`, `{{name}}` is the attribute/key name. For others,
  196. is the same as the input. You can customize a validator name using:
  197. ```php
  198. v::date('Y-m-d')->between('1980-02-02', 'now')->setName('Member Since');
  199. ```
  200. ## Zend/Symfony validators
  201. It is also possible to reuse validators from other frameworks if they are installed:
  202. ```php
  203. $hostnameValidator = v::zend('Hostname')->assert('google.com');
  204. $timeValidator = v::sf('Time')->assert('22:00:01');
  205. ```
  206. ## Validation methods
  207. We've seen `validate()` that returns true or false and `assert()` that throws a complete
  208. validation report. There is also a `check()` method that returns an Exception
  209. only with the first error found:
  210. ```php
  211. use Respect\Validation\Exceptions\ValidationException;
  212. try {
  213. $usernameValidator->check('really messed up screen#name');
  214. } catch(ValidationException $exception) {
  215. echo $exception->getMainMessage();
  216. }
  217. ```
  218. Message:
  219. ```no-highlight
  220. "really messed up screen#name" must contain only letters (a-z) and digits (0-9)
  221. ```
  222. ***
  223. See also:
  224. - [Contributing](../CONTRIBUTING.md)
  225. - [Installation](INSTALL.md)
  226. - [License](../LICENSE.md)
  227. - [Validators](VALIDATORS.md)
  228. - [Changelog](../CHANGELOG.md)