05-Validators.txt 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. = Validators =
  2. [[PageOutline]]
  3. Validators help you to validate an input before perstisting it to the database. In Propel, validators are rules describing what type of data a column accepts. Validators are referenced in the `schema.xml` file, using `<validator>` tags.
  4. Validators are applied at the PHP level, they are not created as constraints on the database itself. That means that if you also use another language to work with the database, the validator rules will not be enforced.
  5. You can also apply multiple rule entries per validator entry in the schema.xml file.
  6. == Overview ==
  7. In the following example, the `username` column is defined to have a minimum length of 4 characters:
  8. {{{
  9. #!xml
  10. <table name="user">
  11. <column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
  12. <column name="username" type="VARCHAR" size="34" required="true" />
  13. <validator column="username">
  14. <rule name="minLength" value="4" message="Username must be at least ${value} characters !" />
  15. </validator>
  16. </table>
  17. }}}
  18. Every column rule is represented by a `<rule>` tag. A `<validator>` is a set of `<rule>` tags bound to a column.
  19. At runtime, you can validate an instance of the model by calling the `validate()` method:
  20. {{{
  21. #!php
  22. <?php
  23. $user = new User();
  24. $user->setUsername("foo"); // only 3 in length, which is too short...
  25. if ($objUser->validate()) {
  26. // no validation errors, so the data can be persisted
  27. $user->save();
  28. } else {
  29. // Something went wrong.
  30. // Use the validationFailures to check what
  31. $failures = $objUser->getValidationFailures();
  32. foreach($failures as $failure) {
  33. echo $objValidationFailure->getMessage() . "<br />\n";
  34. }
  35. }
  36. }}}
  37. `validate()` returns a boolean. If the validation failed, you can access the array `ValidationFailed` objects by way of the `getValidationFailures()` method. Each `ValidationFailed` instance gives access to the column, the messagen and the validator that caused the failure.
  38. == Core Validators ==
  39. Propel bundles a set of validatorts that should help you deal with the most common cases.
  40. === !MatchValidator ===
  41. The `MatchValidator` is used to run a regular expression of choice against the column. Note that this is a `preg`, not `ereg` (check [http://www.php.net/preg_match the preg_match documentation] for more information about regexps).
  42. {{{
  43. #!xml
  44. <validator column="username">
  45. <!-- allow strings that match the email adress pattern -->
  46. <rule
  47. name="match"
  48. value="/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/"
  49. message="Please enter a valid email address." />
  50. </validator>
  51. }}}
  52. === !NotMatchValidator ===
  53. Opposite of `MatchValidator, this validator returns false if the regex returns true
  54. {{{
  55. #!xml
  56. <column name="ISBN" type="VARCHAR" size="20" required="true" />
  57. <validator column="ISBN">
  58. <!-- disallow everything that's not a digit or minus -->
  59. <rule
  60. name="notMatch"
  61. value="/[^\d-]+/"
  62. message="Please enter a valid ISBN" />
  63. </validator>
  64. }}}
  65. === !MaxLengthValidator ===
  66. When you want to limit the size of the string to be inserted in a column, use the `MaxLengthValidator`. Internally, it uses `strlen()` to get the length of the string. For instance, some database completely ignore the lentgh of `LONGVARCHAR` columns; you can enforce it using a validator:
  67. {{{
  68. #!xml
  69. <column name="comment" type="LONGVARCHAR" required="true" />
  70. <validator column="comment">
  71. <rule
  72. name="maxLength"
  73. value="1024"
  74. message="Comments can be no larger than ${value} in size" />
  75. </validator>
  76. }}}
  77. '''Tip''': If you have specified the `size` attribute in the `<column>` tag, you don't have to specify the `value` attribute in the validator rule again, as this is done automatically.
  78. === !MinLengthValidator ===
  79. {{{
  80. #!xml
  81. <column name="username" type="VARCHAR" size="34" required="true" />
  82. <validator column="username">
  83. <rule
  84. name="minLength"
  85. value="4"
  86. message="Username must be at least ${value} characters !" />
  87. </validator>
  88. }}}
  89. === !MaxValueValidator ===
  90. To limit the value of an integer column, use the `MaxValueValidator`. Note that this validator uses a non-strict comparison ('less than or equal'):
  91. {{{
  92. #!xml
  93. <column name="security_level" type="INTEGER" required="true" />
  94. <validator column="security_level">
  95. <rule
  96. name="maxValue"
  97. value="1000"
  98. message="Maximum security level is ${value} !" />
  99. </validator>
  100. }}}
  101. === !MinValueValidator ===
  102. {{{
  103. #!xml
  104. <column name="cost" type="INTEGER" required="true" />
  105. <validator column="cost">
  106. <rule
  107. name="minValue"
  108. value="0"
  109. message="Products can cost us negative $ can they?" />
  110. </validator>
  111. }}}
  112. '''Tip''': You can run multiple validators against a single column.
  113. {{{
  114. #!xml
  115. <column name="security_level" type="INTEGER" required="true" default="10" />
  116. <validator column="security_level" translate="none">
  117. <rule
  118. name="minValue"
  119. value="0"
  120. message="Invalid security level, range: 0-10" />
  121. <rule
  122. name="maxValue"
  123. value="10"
  124. message="Invalid security level, range: 0-10" />
  125. </validator>
  126. }}}
  127. === !RequiredValidator ===
  128. This validtor checks the same rule as a `required=true` on the column at the database level. However it will not give you a clean error to work with.
  129. {{{
  130. #!xml
  131. <column name="username" type="VARCHAR" size="25" required="true" />
  132. <validator column="username">
  133. <rule
  134. name="required"
  135. message="Username is required." />
  136. </validator>
  137. }}}
  138. === !UniqueValidator ===
  139. To check whether the value already exists in the table, use the `UniqueValidator`:
  140. {{{
  141. #!xml
  142. <column name="username" type="VARCHAR" size="25" required="true" />
  143. <validator column="username">
  144. <rule
  145. name="unique"
  146. message="Username already exists !" />
  147. </validator>
  148. }}}
  149. === !ValidValuesValidator ===
  150. This rule restricts the valid values to a list delimited by a pipe ('|').
  151. {{{
  152. #!xml
  153. <column name="address_type" type="VARCHAR" required="true" default="delivery" />
  154. <validator column="address_type">
  155. <rule
  156. name="validValues"
  157. value="account|delivery"
  158. message="Please select a valid address type." />
  159. </validator>
  160. }}}
  161. === !TypeValidator ===
  162. Restrict values to a certain PHP type using the `TypeValidator`:
  163. {{{
  164. #!xml
  165. <column name="username" type="VARCHAR" size="25" required="true" />
  166. <validator column="username">
  167. <rule
  168. name="type"
  169. value="string"
  170. message="Username must be a string" />
  171. </validator>
  172. }}}
  173. == Adding A Custom Validator ==
  174. You can easily add a custom validator. A validator is a class extending `BasicValidator` providing a public `isValid()` method. For instance:
  175. {{{
  176. #!php
  177. <?php
  178. require_once 'propel/validator/BasicValidator.php';
  179. /**
  180. * A simple validator for email fields.
  181. *
  182. * @package propel.validator
  183. */
  184. class EmailValidator implements BasicValidator
  185. {
  186. public function isValid(ValidatorMap $map, $str)
  187. {
  188. return preg_match('/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i', $str) !== 0;
  189. }
  190. }
  191. }}}
  192. The `ValidatorMap` instance passed as parameter gives you access to the rules attribute as defined in the `<rule>` tag. So `$map->getValue()` returns the `value` attribute.
  193. '''Tip''': Make sure that `isValid()` returns a boolean, so really true or false. Propel is very strict about this. Returning a mixed value just won't do.
  194. To enable the new validator on a column, add a corresponding `<rule>` in your schema and use 'class' as the rule `name`.
  195. {{{
  196. #!xml
  197. <validator column="<column_name>">
  198. <rule name="class" class="my.dir.EmailValidator" message="Invalid e-mail address!" />
  199. </validator>
  200. }}}
  201. The `class` attribute of the `<rule>` tag should contain a path to the validator class accessible from the include_path, where the directory separator is replaced by a dot.