Zend_Validate-WritingValidators.xml 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. <sect1 id="zend.validate.writing_validators">
  2. <title>Pisanie weryfikatorów</title>
  3. <para>
  4. Zend_Validate zapewnia zestaw najczęściej potrzebnych weryfikatorów, ale
  5. programiści często potrzebują napisać własne weryfikatory dla ich
  6. szczególnych zastosowań. Zadanie pisania własnego filtru jest opisane w
  7. tej sekcji.
  8. </para>
  9. <para>
  10. Interfejs <code>Zend_Validate_Interface</code> definiuje trzy metody,
  11. <code>isValid()</code>, <code>getMessages()</code> oraz
  12. <code>getErrors()</code>, które mogą być zaimplementowane przez klasę
  13. użytkownika w celu utworzenia własnych obiektów weryfikujących. Obiekt,
  14. który implementuje interfejs <code>Zend_Validate_Interface</code>
  15. może być dodany do łańcucha weryfikatorów za pomocą metody
  16. <code>Zend_Validate::addValidator()</code>.
  17. Taki obiekt może być także użyty przez klasę
  18. <link linkend="zend.filter.input"><code>Zend_Filter_Input</code></link>.
  19. </para>
  20. <para>
  21. As you may already have inferred from the above description of <code>Zend_Validate_Interface</code>,
  22. validation classes provided with Zend Framework return a boolean value for whether or not a value validates
  23. successfully. They also provide information about <emphasis role="bold">why</emphasis> a value failed
  24. validation. The availability of the reasons for validation failures may be valuable to an application for
  25. various purposes, such as providing statistics for usability analysis.
  26. </para>
  27. <para>
  28. Basic validation failure message functionality is implemented in <code>Zend_Validate_Abstract</code>. To
  29. include this functionality when creating a validation class, simply extend
  30. <code>Zend_Validate_Abstract</code>. In the extending class you would implement the
  31. <code>isValid()</code> method logic and define the message variables and message templates that correspond to
  32. the types of validation failures that can occur. If a value fails your validation tests, then
  33. <code>isValid()</code> should return <code>false</code>. If the value passes your validation tests, then
  34. <code>isValid()</code> should return <code>true</code>.
  35. </para>
  36. <para>
  37. In general, the <code>isValid()</code> method should not throw any exceptions, except where it is impossible
  38. to determine whether or not the input value is valid. A few examples of reasonable cases for throwing an
  39. exception might be if a file cannot be opened, an LDAP server could not be contacted, or a database
  40. connection is unavailable, where such a thing may be required for validation success or failure to be
  41. determined.
  42. </para>
  43. <example id="zend.validate.writing_validators.example.simple">
  44. <title>Creating a Simple Validation Class</title>
  45. <para>
  46. The following example demonstrates how a very simple custom validator might be written. In this case the
  47. validation rules are simply that the input value must be a floating point value.
  48. <programlisting role="php"><![CDATA[
  49. class MyValid_Float extends Zend_Validate_Abstract
  50. {
  51. const FLOAT = 'float';
  52. protected $_messageTemplates = array(
  53. self::FLOAT => "'%value%' is not a floating point value"
  54. );
  55. public function isValid($value)
  56. {
  57. $this->_setValue($value);
  58. if (!is_float($value)) {
  59. $this->_error();
  60. return false;
  61. }
  62. return true;
  63. }
  64. }
  65. ]]>
  66. </programlisting>
  67. The class defines a template for its single validation failure message, which includes the built-in magic
  68. parameter, <code>%value%</code>. The call to <code>_setValue()</code> prepares the object to insert the
  69. tested value into the failure message automatically, should the value fail validation. The call to
  70. <code>_error()</code> tracks a reason for validation failure. Since this class only defines one failure
  71. message, it is not necessary to provide <code>_error()</code> with the name of the failure message
  72. template.
  73. </para>
  74. </example>
  75. <example id="zend.validate.writing_validators.example.conditions.dependent">
  76. <title>Writing a Validation Class having Dependent Conditions</title>
  77. <para>
  78. The following example demonstrates a more complex set of validation rules, where it is required that the
  79. input value be numeric and within the range of minimum and maximum boundary values. An input value would
  80. fail validation for exactly one of the following reasons:
  81. <itemizedlist>
  82. <listitem>
  83. <para>The input value is not numeric.</para>
  84. </listitem>
  85. <listitem>
  86. <para>The input value is less than the minimum allowed value.</para>
  87. </listitem>
  88. <listitem>
  89. <para>The input value is more than the maximum allowed value.</para>
  90. </listitem>
  91. </itemizedlist>
  92. </para>
  93. <para>
  94. These validation failure reasons are then translated to definitions in the class:
  95. <programlisting role="php"><![CDATA[
  96. class MyValid_NumericBetween extends Zend_Validate_Abstract
  97. {
  98. const MSG_NUMERIC = 'msgNumeric';
  99. const MSG_MINIMUM = 'msgMinimum';
  100. const MSG_MAXIMUM = 'msgMaximum';
  101. public $minimum = 0;
  102. public $maximum = 100;
  103. protected $_messageVariables = array(
  104. 'min' => 'minimum',
  105. 'max' => 'maximum'
  106. );
  107. protected $_messageTemplates = array(
  108. self::MSG_NUMERIC => "'%value%' is not numeric",
  109. self::MSG_MINIMUM => "'%value%' must be at least '%min%'",
  110. self::MSG_MAXIMUM => "'%value%' must be no more than '%max%'"
  111. );
  112. public function isValid($value)
  113. {
  114. $this->_setValue($value);
  115. if (!is_numeric($value)) {
  116. $this->_error(self::MSG_NUMERIC);
  117. return false;
  118. }
  119. if ($value < $this->minimum) {
  120. $this->_error(self::MSG_MINIMUM);
  121. return false;
  122. }
  123. if ($value > $this->maximum) {
  124. $this->_error(self::MSG_MAXIMUM);
  125. return false;
  126. }
  127. return true;
  128. }
  129. }
  130. ]]>
  131. </programlisting>
  132. The public properties <code>$minimum</code> and <code>$maximum</code> have been established to provide
  133. the minimum and maximum boundaries, respectively, for a value to successfully validate. The class also
  134. defines two message variables that correspond to the public properties and allow <code>min</code> and
  135. <code>max</code> to be used in message templates as magic parameters, just as with <code>value</code>.
  136. </para>
  137. <para>
  138. Note that if any one of the validation checks in <code>isValid()</code> fails, an appropriate failure
  139. message is prepared, and the method immediately returns <code>false</code>. These validation rules are
  140. therefore sequentially dependent. That is, if one test should fail, there is no need to test any
  141. subsequent validation rules. This need not be the case, however. The following example illustrates how to
  142. write a class having independent validation rules, where the validation object may return multiple
  143. reasons why a particular validation attempt failed.
  144. </para>
  145. </example>
  146. <example id="zend.validate.writing_validators.example.conditions.independent">
  147. <title>Validation with Independent Conditions, Multiple Reasons for Failure</title>
  148. <para>
  149. Consider writing a validation class for password strength enforcement - when a user is required to choose
  150. a password that meets certain criteria for helping secure user accounts. Let us assume that the password
  151. security criteria enforce that the password:
  152. <itemizedlist>
  153. <listitem>
  154. <para>is at least 8 characters in length,</para>
  155. </listitem>
  156. <listitem>
  157. <para>contains at least one uppercase letter,</para>
  158. </listitem>
  159. <listitem>
  160. <para>contains at least one lowercase letter,</para>
  161. </listitem>
  162. <listitem>
  163. <para>and contains at least one digit character.</para>
  164. </listitem>
  165. </itemizedlist>
  166. </para>
  167. <para>
  168. The following class implements these validation criteria:
  169. <programlisting role="php"><![CDATA[
  170. class MyValid_PasswordStrength extends Zend_Validate_Abstract
  171. {
  172. const LENGTH = 'length';
  173. const UPPER = 'upper';
  174. const LOWER = 'lower';
  175. const DIGIT = 'digit';
  176. protected $_messageTemplates = array(
  177. self::LENGTH => "'%value%' must be at least 8 characters in length",
  178. self::UPPER => "'%value%' must contain at least one uppercase letter",
  179. self::LOWER => "'%value%' must contain at least one lowercase letter",
  180. self::DIGIT => "'%value%' must contain at least one digit character"
  181. );
  182. public function isValid($value)
  183. {
  184. $this->_setValue($value);
  185. $isValid = true;
  186. if (strlen($value) < 8) {
  187. $this->_error(self::LENGTH);
  188. $isValid = false;
  189. }
  190. if (!preg_match('/[A-Z]/', $value)) {
  191. $this->_error(self::UPPER);
  192. $isValid = false;
  193. }
  194. if (!preg_match('/[a-z]/', $value)) {
  195. $this->_error(self::LOWER);
  196. $isValid = false;
  197. }
  198. if (!preg_match('/\d/', $value)) {
  199. $this->_error(self::DIGIT);
  200. $isValid = false;
  201. }
  202. return $isValid;
  203. }
  204. }
  205. ]]>
  206. </programlisting>
  207. Note that the four criteria tests in <code>isValid()</code> do not immediately return <code>false</code>.
  208. This allows the validation class to provide <emphasis role="bold">all</emphasis> of the reasons that the
  209. input password failed to meet the validation requirements. If, for example, a user were to input the
  210. string "<code>#$%</code>" as a password, <code>isValid()</code> would cause all four validation failure
  211. messages to be returned by a subsequent call to <code>getMessages()</code>.
  212. </para>
  213. </example>
  214. </sect1>