Zend_Validate-ValidatorChains.xml 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!-- Reviewed: no -->
  3. <sect1 id="zend.validate.validator_chains">
  4. <title>Validator Chains</title>
  5. <para>
  6. Often multiple validations should be applied to some value in a particular order. The
  7. following code demonstrates a way to solve the example from the
  8. <link linkend="zend.validate.introduction">introduction</link>, where a username must be
  9. between 6 and 12 alphanumeric characters:
  10. <programlisting language="php"><![CDATA[
  11. // Create a validator chain and add validators to it
  12. $validatorChain = new Zend_Validate();
  13. $validatorChain->addValidator(new Zend_Validate_StringLength(6, 12))
  14. ->addValidator(new Zend_Validate_Alnum());
  15. // Validate the username
  16. if ($validatorChain->isValid($username)) {
  17. // username passed validation
  18. } else {
  19. // username failed validation; print reasons
  20. foreach ($validatorChain->getMessages() as $message) {
  21. echo "$message\n";
  22. }
  23. }
  24. ]]></programlisting>
  25. Validators are run in the order they were added to <classname>Zend_Validate</classname>. In
  26. the above example, the username is first checked to ensure that its length is between 6 and
  27. 12 characters, and then it is checked to ensure that it contains only alphanumeric
  28. characters. The second validation, for alphanumeric characters, is performed regardless of
  29. whether the first validation, for length between 6 and 12 characters, succeeds. This means
  30. that if both validations fail, <code>getMessages()</code> will return failure messages from
  31. both validators.
  32. </para>
  33. <para>
  34. In some cases it makes sense to have a validator break the chain if its validation process
  35. fails. <classname>Zend_Validate</classname> supports such use cases with the second
  36. parameter to the <code>addValidator()</code> method. By setting
  37. <code>$breakChainOnFailure</code> to <constant>TRUE</constant>, the added validator will break the
  38. chain execution upon failure, which avoids running any other validations that are determined
  39. to be unnecessary or inappropriate for the situation. If the above example were written as
  40. follows, then the alphanumeric validation would not occur if the string length validation
  41. fails:
  42. <programlisting language="php"><![CDATA[
  43. $validatorChain->addValidator(new Zend_Validate_StringLength(6, 12), true)
  44. ->addValidator(new Zend_Validate_Alnum());
  45. ]]></programlisting>
  46. </para>
  47. <para>
  48. Any object that implements <classname>Zend_Validate_Interface</classname> may be used in a
  49. validator chain.
  50. </para>
  51. </sect1>
  52. <!--
  53. vim:se ts=4 sw=4 et:
  54. -->