sfValidatorString.class.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfValidatorString validates a string. It also converts the input value to a string.
  11. *
  12. * @package symfony
  13. * @subpackage validator
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. * @version SVN: $Id: sfValidatorString.class.php 12641 2008-11-04 18:22:00Z fabien $
  16. */
  17. class sfValidatorString extends sfValidatorBase
  18. {
  19. /**
  20. * Configures the current validator.
  21. *
  22. * Available options:
  23. *
  24. * * max_length: The maximum length of the string
  25. * * min_length: The minimum length of the string
  26. *
  27. * Available error codes:
  28. *
  29. * * max_length
  30. * * min_length
  31. *
  32. * @param array $options An array of options
  33. * @param array $messages An array of error messages
  34. *
  35. * @see sfValidatorBase
  36. */
  37. protected function configure($options = array(), $messages = array())
  38. {
  39. $this->addMessage('max_length', '"%value%" is too long (%max_length% characters max).');
  40. $this->addMessage('min_length', '"%value%" is too short (%min_length% characters min).');
  41. $this->addOption('max_length');
  42. $this->addOption('min_length');
  43. $this->setOption('empty_value', '');
  44. }
  45. /**
  46. * @see sfValidatorBase
  47. */
  48. protected function doClean($value)
  49. {
  50. $clean = (string) $value;
  51. $length = function_exists('mb_strlen') ? mb_strlen($clean, $this->getCharset()) : strlen($clean);
  52. if ($this->hasOption('max_length') && $length > $this->getOption('max_length'))
  53. {
  54. throw new sfValidatorError($this, 'max_length', array('value' => $value, 'max_length' => $this->getOption('max_length')));
  55. }
  56. if ($this->hasOption('min_length') && $length < $this->getOption('min_length'))
  57. {
  58. throw new sfValidatorError($this, 'min_length', array('value' => $value, 'min_length' => $this->getOption('min_length')));
  59. }
  60. return $clean;
  61. }
  62. }