I've a form with 2 text-fields, namely minimum-amount & maximum-amount. I would like to know whether it is possible for me to compare the values in text-field "minimum-amount" with the value in text-field "maximum-amount" and vice-versa using validators in Zendform.
just create your own validator, the isValid method of the validator will get the value of the field the validator is attached to plus the whole context of the form, which is an array of values of all other form fields. additionally you can add functions to the validator to set the context field and if it should be less, equal, greater or even pass a function to compare...
here some example code (not tested)
<?php
namespace My\Validator;
class MinMaxComp extends AbstractValidator
{
const ERROR_NOT_SMALLER = 'not_smaller';
const ERROR_NOT_GREATER = 'not_greater';
const ERROR_CONFIG = 'wrong_config';
const TYPE_SMALLER = 0;
const TYPE_GREATER = 1;
protected $messageTemplates = array(
self::ERROR_NOT_SMALLER => "Blah",
self::ERROR_NOT_GREATER => "Blah",
self::WRONG_CONFIG => "Blah",
);
protected $type;
protected $contextField;
public function setType($type)
{
$this->type = $type;
}
public function setContextField($fieldName)
{
$this->contextField = $fieldName;
}
public function isValid($value, $context = null)
{
$this->setValue($value);
if (!is_array($context) || !isset($context[$this->contextField])) {
return false;
}
if ($this->type === self::TYPE_SMALLER) {
if (!$result = ($value < $context[$this->contextField])) {
$this->error(self::ERROR_NOT_SMALLER);
}
} else if ($this->type === self::TYPE_GREATER) {
if (!$result = ($value > $context[$this->contextField])) {
$this->error(self::ERROR_NOT_GREATER);
}
} else {
$result = false;
$this->error(self::ERROR_CONFIG);
}
return $result;
}
}