ConditionalNotEmpty.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. /**
  3. * Check if a field is empty but only when specific fields have specific values
  4. */
  5. class ConditionalNotEmpty extends Zend_Validate_Abstract
  6. {
  7. const KEY_IS_EMPTY = 'keyIsEmpty';
  8. protected $_messageTemplates;
  9. protected $_fieldValues;
  10. /**
  11. * Constructs a new ConditionalNotEmpty validator.
  12. *
  13. * @param array $fieldValues - the names and expected values of the fields we're depending on;
  14. * E.g., if we have a field that should only be validated when two other
  15. * fields PARENT_1 and PARENT_2 have values of '1' and '0' respectively, then
  16. * $fieldValues should contain ('PARENT_1'=>'1', 'PARENT_2'=>'0')
  17. */
  18. public function __construct($fieldValues)
  19. {
  20. $this->_fieldValues = $fieldValues;
  21. $this->_messageTemplates = array(
  22. self::KEY_IS_EMPTY => _("Value is required and can't be empty")
  23. );
  24. }
  25. /**
  26. * Implements Zend_Validate_Abstract.
  27. * Given names and expected values of the fields we're depending on ($_fieldValues),
  28. * this function returns true if the expected values doesn't match the actual user input,
  29. * or if $value is not empty. Returns false otherwise.
  30. *
  31. * @param String $value - this field's value
  32. * @param array $context - names and values of the rest of the fields in this form
  33. * @return boolean - true if valid; false otherwise
  34. */
  35. public function isValid($value, $context = null)
  36. {
  37. if ($value != "") {
  38. return true;
  39. }
  40. if (is_array($context)) {
  41. foreach ($this->_fieldValues as $fieldName=>$fieldValue) {
  42. if (!isset($context[$fieldName]) || $context[$fieldName] != $fieldValue) {
  43. return true;
  44. }
  45. }
  46. } elseif (is_string($context)) {
  47. if (!isset($context) || $context != $fieldValue) {
  48. return true;
  49. }
  50. }
  51. $this->_error(self::KEY_IS_EMPTY);
  52. return false;
  53. }
  54. }