別のフォーム要素の値に基づいて数値範囲を検証する最良の方法は何ですか? ユーザーが割引タイプとして「パーセンテージ」を選択した場合、割引額は 140 ではなく 0 から 100 の間である必要があります。問題は、別のフォーム要素の値を渡しているようです。
また、同様のトピックを扱っている他のリソースも見ましたが、おそらく関連性があまりありません。 別のフィールドの値に基づいて Zend_Form のフィールドを検証する方法は?
Form.php
$isValid = new Application_Model_Validate();
$discount = $this->createElement('text', 'discount')
->setLabel('Discount Amount')
->setDescription("Enter an amount in the format \"200.00\" ")
->setRequired(true)
->setDecorators(array('Description', 'ViewHelper', 'Errors',
array('HTMLTag', array('tag' => 'dd')),
array('Label', array('tag' => 'dt'))));
$discount->addValidators(array(array('Float')), $isValid->isValid(new Zend_Validate_Between(array('min' => '0', 'max' => '100')), $discountType));
$this->addElement($discount);
Application_Model_Validate.php
Require_once 'Zend/Validate/Abstract.php';
class Application_Model_Validate extends Zend_Validate_Abstract
{
/*
* Validation failure message key
*/
const INVALID_PERCENTAGE = 'InvalidPercentage';
/*
* Validation failure message template definitions
*/
protected $_messageTemplates = array(
self::INVALID_PERCENTAGE => 'Please enter a percentage greater than 0 and up to 100.'
);
protected $_percentageOption;
protected $_percentageValue;
/*
* Defined by Zend_Validate_Interface
* Validate the percentage parameters
*/
public function isValid($value, $context = null)
{
$this->_setValue($value);
/*
* If context key is valid, return true
*/
if(is_array($context))
{
if (isset($context['percentage']) && ($value))
{
return true;
}
}
$this->_error(self::INVALID_PERCENTAGE);
return false;
}
さらに情報が必要な場合は、言ってください。