Zend_Validate-WritingValidators.xml 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.validate.writing_validators">
  4. <title>Writing Validators</title>
  5. <para>
  6. Zend_Validate supplies a set of commonly needed validators, but inevitably, developers will
  7. wish to write custom validators for their particular needs. The task of writing a custom
  8. validator is described in this section.
  9. </para>
  10. <para>
  11. <classname>Zend_Validate_Interface</classname> defines three methods,
  12. <code>isValid()</code>, <code>getMessages()</code>, and <code>getErrors()</code>, that may
  13. be implemented by user classes in order to create custom validation objects. An object that
  14. implements <classname>Zend_Validate_Interface</classname> interface may be added to a
  15. validator chain with <classname>Zend_Validate::addValidator()</classname>. Such objects may
  16. also be used with <link
  17. linkend="zend.filter.input"><classname>Zend_Filter_Input</classname></link>.
  18. </para>
  19. <para>
  20. As you may already have inferred from the above description of
  21. <classname>Zend_Validate_Interface</classname>, validation classes provided with Zend
  22. Framework return a boolean value for whether or not a value validates successfully. They
  23. also provide information about <emphasis>why</emphasis> a value failed validation. The
  24. 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
  29. <classname>Zend_Validate_Abstract</classname>. To include this functionality when creating a
  30. validation class, simply extend <classname>Zend_Validate_Abstract</classname>. In the
  31. extending class you would implement the <code>isValid()</code> method logic and define the
  32. message variables and message templates that correspond to the types of validation failures
  33. that can occur. If a value fails your validation tests, then <code>isValid()</code> should
  34. return <constant>FALSE</constant>. If the value passes your validation tests, then
  35. <code>isValid()</code> should return <constant>TRUE</constant>.
  36. </para>
  37. <para>
  38. In general, the <code>isValid()</code> method should not throw any exceptions, except where
  39. it is impossible to determine whether or not the input value is valid. A few examples of
  40. reasonable cases for throwing an exception might be if a file cannot be opened, an LDAP
  41. server could not be contacted, or a database connection is unavailable, where such a thing
  42. may be required for validation success or failure to be determined.
  43. </para>
  44. <example id="zend.validate.writing_validators.example.simple">
  45. <title>Creating a Simple Validation Class</title>
  46. <para>
  47. The following example demonstrates how a very simple custom validator might be written.
  48. In this case the validation rules are simply that the input value must be a floating
  49. point value.
  50. <programlisting language="php"><![CDATA[
  51. class MyValid_Float extends Zend_Validate_Abstract
  52. {
  53. const FLOAT = 'float';
  54. protected $_messageTemplates = array(
  55. self::FLOAT => "'%value%' is not a floating point value"
  56. );
  57. public function isValid($value)
  58. {
  59. $this->_setValue($value);
  60. if (!is_float($value)) {
  61. $this->_error();
  62. return false;
  63. }
  64. return true;
  65. }
  66. }
  67. ]]></programlisting>
  68. The class defines a template for its single validation failure message, which includes
  69. the built-in magic parameter, <code>%value%</code>. The call to <code>_setValue()</code>
  70. prepares the object to insert the tested value into the failure message automatically,
  71. should the value fail validation. The call to <code>_error()</code> tracks a reason for
  72. validation failure. Since this class only defines one failure message, it is not
  73. necessary to provide <code>_error()</code> with the name of the failure message
  74. template.
  75. </para>
  76. </example>
  77. <example id="zend.validate.writing_validators.example.conditions.dependent">
  78. <title>Writing a Validation Class having Dependent Conditions</title>
  79. <para>
  80. The following example demonstrates a more complex set of validation rules, where it is
  81. required that the input value be numeric and within the range of minimum and maximum
  82. boundary values. An input value would fail validation for exactly one of the following
  83. reasons:
  84. <itemizedlist>
  85. <listitem>
  86. <para>The input value is not numeric.</para>
  87. </listitem>
  88. <listitem>
  89. <para>The input value is less than the minimum allowed value.</para>
  90. </listitem>
  91. <listitem>
  92. <para>The input value is more than the maximum allowed value.</para>
  93. </listitem>
  94. </itemizedlist>
  95. </para>
  96. <para>
  97. These validation failure reasons are then translated to definitions in the class:
  98. <programlisting language="php"><![CDATA[
  99. class MyValid_NumericBetween extends Zend_Validate_Abstract
  100. {
  101. const MSG_NUMERIC = 'msgNumeric';
  102. const MSG_MINIMUM = 'msgMinimum';
  103. const MSG_MAXIMUM = 'msgMaximum';
  104. public $minimum = 0;
  105. public $maximum = 100;
  106. protected $_messageVariables = array(
  107. 'min' => 'minimum',
  108. 'max' => 'maximum'
  109. );
  110. protected $_messageTemplates = array(
  111. self::MSG_NUMERIC => "'%value%' is not numeric",
  112. self::MSG_MINIMUM => "'%value%' must be at least '%min%'",
  113. self::MSG_MAXIMUM => "'%value%' must be no more than '%max%'"
  114. );
  115. public function isValid($value)
  116. {
  117. $this->_setValue($value);
  118. if (!is_numeric($value)) {
  119. $this->_error(self::MSG_NUMERIC);
  120. return false;
  121. }
  122. if ($value < $this->minimum) {
  123. $this->_error(self::MSG_MINIMUM);
  124. return false;
  125. }
  126. if ($value > $this->maximum) {
  127. $this->_error(self::MSG_MAXIMUM);
  128. return false;
  129. }
  130. return true;
  131. }
  132. }
  133. ]]></programlisting>
  134. The public properties <code>$minimum</code> and <code>$maximum</code> have been
  135. established to provide the minimum and maximum boundaries, respectively, for a value to
  136. successfully validate. The class also defines two message variables that correspond to
  137. the public properties and allow <code>min</code> and <code>max</code> to be used in
  138. message templates as magic parameters, just as with <code>value</code>.
  139. </para>
  140. <para>
  141. Note that if any one of the validation checks in <code>isValid()</code> fails, an
  142. appropriate failure message is prepared, and the method immediately returns
  143. <constant>FALSE</constant>. These validation rules are therefore sequentially dependent. That
  144. is, if one test should fail, there is no need to test any subsequent validation rules.
  145. This need not be the case, however. The following example illustrates how to write a
  146. class having independent validation rules, where the validation object may return
  147. multiple reasons why a particular validation attempt failed.
  148. </para>
  149. </example>
  150. <example id="zend.validate.writing_validators.example.conditions.independent">
  151. <title>Validation with Independent Conditions, Multiple Reasons for Failure</title>
  152. <para>
  153. Consider writing a validation class for password strength enforcement - when a user is
  154. required to choose a password that meets certain criteria for helping secure user
  155. accounts. Let us assume that the password security criteria enforce that the password:
  156. <itemizedlist>
  157. <listitem>
  158. <para>is at least 8 characters in length,</para>
  159. </listitem>
  160. <listitem>
  161. <para>contains at least one uppercase letter,</para>
  162. </listitem>
  163. <listitem>
  164. <para>contains at least one lowercase letter,</para>
  165. </listitem>
  166. <listitem>
  167. <para>and contains at least one digit character.</para>
  168. </listitem>
  169. </itemizedlist>
  170. </para>
  171. <para>
  172. The following class implements these validation criteria:
  173. <programlisting language="php"><![CDATA[
  174. class MyValid_PasswordStrength extends Zend_Validate_Abstract
  175. {
  176. const LENGTH = 'length';
  177. const UPPER = 'upper';
  178. const LOWER = 'lower';
  179. const DIGIT = 'digit';
  180. protected $_messageTemplates = array(
  181. self::LENGTH => "'%value%' must be at least 8 characters in length",
  182. self::UPPER => "'%value%' must contain at least one uppercase letter",
  183. self::LOWER => "'%value%' must contain at least one lowercase letter",
  184. self::DIGIT => "'%value%' must contain at least one digit character"
  185. );
  186. public function isValid($value)
  187. {
  188. $this->_setValue($value);
  189. $isValid = true;
  190. if (strlen($value) < 8) {
  191. $this->_error(self::LENGTH);
  192. $isValid = false;
  193. }
  194. if (!preg_match('/[A-Z]/', $value)) {
  195. $this->_error(self::UPPER);
  196. $isValid = false;
  197. }
  198. if (!preg_match('/[a-z]/', $value)) {
  199. $this->_error(self::LOWER);
  200. $isValid = false;
  201. }
  202. if (!preg_match('/\d/', $value)) {
  203. $this->_error(self::DIGIT);
  204. $isValid = false;
  205. }
  206. return $isValid;
  207. }
  208. }
  209. ]]></programlisting>
  210. Note that the four criteria tests in <code>isValid()</code> do not immediately return
  211. <constant>FALSE</constant>. This allows the validation class to provide <emphasis>all</emphasis>
  212. of the reasons that the input password failed to meet the validation requirements. if,
  213. for example, a user were to input the string "<code>#$%</code>" as a password,
  214. <code>isValid()</code> would cause all four validation failure messages to be returned
  215. by a subsequent call to <code>getMessages()</code>.
  216. </para>
  217. </example>
  218. </sect1>
  219. <!--
  220. vim:se ts=4 sw=4 et:
  221. -->