我想做什么?
我有三个字段(1 个隐藏,一个 id),用户必须完成另外两个字段之一才能通过验证。
因此,如果两个字段都为空,则用户应该无法通过验证,但如果一个已完成,则通过。
1 2 3
A 0 B 真
AB 0 真
A 0 0 假
我正在使用 CakePHP v2.1.3,因此可以访问新的验证规则增强功能。
问题
我似乎找不到同时检查两个字段的可靠方法。到目前为止,我已经尝试$this->data
从 中model
并发现验证一次只传递一个数据实例。所以似乎没有办法比较这些领域。
到目前为止我所拥有的
/**
* Custom validation to see if either of the two fields are set, if neither are, then we fail, if at least one is, we pass
* @param array $check
* @return boolean
*/
public function checkAttributes($check){
var_dump($check);
var_dump($this->data);
echo "<hr>";
// Check for an id value picked from a list
if(@is_numeric($check['attribute_value_id']) && isset($this->data['AdvertAttributeValue']['attribute_value_id'])){
return true;
}
// Check for a date value selected
if(@is_array($check['attribute_value_text']) && isset($this->data['AdvertAttributeValue']['attribute_value_text'])){
return true;
}
// Check for a text value
if(@is_string($check['attribute_value_text']) && isset($this->data['AdvertAttributeValue']['attribute_value_text'])){
return true;
}
return false;
}
这似乎不起作用,因为我认为它无法检查$this->data
,因为它的实例不包含所有相关字段。
我还应该提到的数据
是我传递了一个大型数字数组。因此这些字段在页面上出现多次,目前为 12 维。所以直接通过它们访问它们$this->data
会很困难,因为它们不是命名维度,而是$this->data['Model'][<num>]['field'] = value
验证
public $validate = array(
'attribute_value_id'=>array(
'notempty'=>array(
'rule'=>'checkAttributes',
'message'=>'Please select a value for your attribute',
'required'=>true,
),
),
'attribute_value_text'=>array(
'notempty'=>array(
'rule'=>'checkAttributes',
'message'=>'You must enter text for this attribute',
'required'=>true,
),
)
);
数据转储
这里我将显示var_dump()
上面的输出。我的模型中有两个验证规则,一个用于attribute_value_id
,一个用于attribute_value_text
// An id field selected from a list
array // $check
'attribute_value_id' => string '1' (length=1)
array // $this->data
'AdvertAttributeValue' =>
array
'attribute_value_id' => string '1' (length=1)
'id' => string '' (length=0)
// A text field
// Validating first time around on the id field
array // $check
'attribute_value_id' => string '' (length=0)
array // $this->data
'AdvertAttributeValue' =>
array
'attribute_value_id' => string '' (length=0)
'id' => string '' (length=0)
'attribute_value_text' => string '50' (length=2)
// Validating second time around on the text field
array // $check
'attribute_value_text' => string '50' (length=2)
array // $this->data
'AdvertAttributeValue' =>
array
'attribute_value_id' => string '' (length=0)
'id' => string '' (length=0)
'attribute_value_text' => string '50' (length=2)
// A date field
array // $check
'attribute_value_id' => string '' (length=0)
array // $this->data
'AdvertAttributeValue' =>
array
'attribute_value_id' => string '' (length=0)
'id' => string '' (length=0)
'attribute_value_text' =>
array
'month' => string '06' (length=2)
'day' => string '28' (length=2)
'year' => string '2012' (length=4)