. */ class Staple_Form_Validate_Length extends Staple_Form_Validator { const DEFAULT_ERROR = 'Field does not meet length requirements.'; const MIN_LENGTH_ERROR = 'Minimum Length Not Met'; const MAX_LENGTH_ERROR = 'Maximum Length Exceeded'; protected $min = 0; protected $max; /** * Accepts a maximum length to validate against. Also accepts an optional minimum length. * Whenever PHP starts supporting method overloading, the variables will be reversed in * order to make more logical sense. * * @param int $max * @param int $min */ public function __construct($limit1, $limit2 = NULL, $usermsg = NULL) { $this->min = (int)$limit1; if(isset($limit2)) { if($limit2 >= $limit1) { $this->max = (int)$limit2; } else { $this->min = (int)$limit2; $this->max = (int)$limit1; } } parent::__construct($usermsg); } /** * @return the $min */ public function getMin() { return $this->min; } /** * @return the $max */ public function getMax() { return $this->max; } /** * @param int $min */ public function setMin($min) { $this->min = $min; return $this; } /** * @param int $max */ public function setMax($max) { $this->max = $max; return $this; } /** * Check for Data Length Validity. * @param mixed $data * @return boolean */ public function check($data) { $data = (string)$data; if(strlen($data) >= $this->min) { if(isset($this->max) && strlen($data) <= $this->max) { return true; } elseif(!isset($this->max)) { return true; } else { $this->addError(self::MAX_LENGTH_ERROR); } } else { $this->addError(self::MIN_LENGTH_ERROR); } //Additionally Add the default error message. //$this->addError(); return false; } /** * (non-PHPdoc) * @see Staple_Form_Validator::clientJQuery() */ public function clientJQuery($fieldType, Staple_Form_Element $field) { switch ($fieldType) { case 'Staple_Form_SelectElement': $fieldid = "#{$field->getId()}"; $valstring = "#{$field->getId()} option:selected"; break; case 'Staple_Form_RadioGroup': $fieldid = "input:radio[name={$field->getName()}]"; $valstring = "input:radio[name={$field->getName()}]:checked"; break; case 'Staple_Form_CheckboxElement': return ''; break; default: $fieldid = "#{$field->getId()}"; $valstring = $fieldid; } $script = "\t//Length Validator for ".addslashes($field->getLabel())."\n"; $script .= "\tif($('$valstring').val().length > {$this->getMax()} || $('$valstring').val().length < {$this->getMin()})\n"; $script .= "\t{\n"; $script .= "\t\terrors.push('".addslashes($field->getLabel()).": \\n{$this->clientJSError()}\\n');\n"; $script .= "\t\t$('$fieldid').addClass('form_error');\n"; $script .= "\t}\n"; $script .= "\telse {\n"; $script .= "\t\t$('$fieldid').removeClass('form_error');\n"; $script .= "\t}\n"; return $script; } } ?>