1: <?php
2:
3: 4: 5:
6: class Quform_Validator_Length extends Quform_Validator_Abstract
7: {
8: const INVALID = 'lengthInvalid';
9: const TOO_SHORT = 'lengthTooShort';
10: const TOO_LONG = 'lengthTooLong';
11:
12: 13: 14: 15: 16: 17: 18:
19: public function isValid($value)
20: {
21: $this->reset();
22:
23: if ( ! is_string($value)) {
24: $this->error(self::INVALID);
25: return false;
26: }
27:
28: $min = is_numeric($this->config('min')) ? $this->config('min') : 0;
29: $max = is_numeric($this->config('max')) && $this->config('max') >= $min ? $this->config('max') : '';
30:
31: $length = Quform::strlen($value);
32:
33: if ($length < $min) {
34: $this->error(self::TOO_SHORT, compact('min', 'length', 'value'));
35: return false;
36: }
37:
38: if (is_numeric($max) && $max < $length) {
39: $this->error(self::TOO_LONG, compact('max', 'length', 'value'));
40: return false;
41: }
42:
43: return true;
44: }
45:
46: 47: 48: 49: 50: 51:
52: public static function getMessageTemplates($key = null)
53: {
54: $messageTemplates = array(
55: self::INVALID => __('Invalid data type, string expected', 'quform'),
56: self::TOO_SHORT => __('Value must be at least %min% characters long', 'quform'),
57: self::TOO_LONG => __('Value must be no longer than %max% characters', 'quform')
58: );
59:
60: if (is_string($key)) {
61: return array_key_exists($key, $messageTemplates) ? $messageTemplates[$key] : null;
62: }
63:
64: return $messageTemplates;
65: }
66:
67: 68: 69: 70: 71: 72:
73: public static function getDefaultConfig($key = null)
74: {
75: $config = apply_filters('quform_default_config_validator_length', array(
76: 'min' => '0',
77: 'max' => '',
78: 'messages' => array(
79: self::INVALID => '',
80: self::TOO_SHORT => '',
81: self::TOO_LONG => ''
82: )
83: ));
84:
85: $config['type'] = 'length';
86:
87: if (Quform::isNonEmptyString($key)) {
88: return Quform::get($config, $key);
89: }
90:
91: return $config;
92: }
93: }
94: