【发布时间】:2019-03-22 10:05:53
【问题描述】:
我在 cakephp 1.3 中有一个模型。我想为我的 example_id 字段设置自定义验证,它使用 example_type 字段的值。如果 example_type 是特定类型(1,而不是 2 或 3),我只想让验证失败。
这是验证变量的示例:
var $validate = array(
'example_type' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Example Type: This is a required field'
),
'numeric' => array(
'rule' => array('numeric'),
'message' => 'Example Type: Please choose from the drop down.'
),
'isSpecificType' => array(
'rule' => array('isSpecificType')
)
),
'example_id' => array(
'range' => array(
'rule' => array('range', -1, 2147483648),
'message' => 'Example ID: Enter number from 0 to 2147483647',
'allowEmpty' => true
),
'numeric' => array(
'rule' => array('numeric'),
'message' => 'Example ID: Numeric only.',
'allowEmpty' => true
),
'is_type' => array(
'rule' => array('exampleNotEmpty', $specific_type_var),
'message' => 'Example ID: You must have an example id if the example type is 1'
)
)
);
然后我将有两个自定义验证函数,isSpecificType 和 exampleNotEmpty。请参阅以下内容:
function isSpecificType($check) {
$specific_type_var = $check['example_type'];
return true;
};
function exampleNotEmpty($check, $type) {
if ($type === 1) {
if (is_null($check['example_id'])) {
return false; //by the way, i realize is_null may not be correct here, but I have the capability to correct this after I am able to run it a few times
}
}
return true;
};
最后,在我的 AppModel 顶部,就在 $validate 声明之前,我创建了变量 $specific_type_var。请参阅以下内容:
var $specific_type_var = 1;
所以,现在,我的问题。我在这一行收到错误:
'rule' => array('exampleNotEmpty', $specific_type_var),
错误是:Parse error: syntax error, unexpected '$specific_type_var' (T_VARIABLE), expecting ')' in /cakephpproject/app/models/example.php on line ##
我在这篇文章中的最后一个问题是:我这样做的方式是否正确?我只是有语法错误吗?或者,我可以直接从另一个字段调用的自定义验证函数内部访问 example_type 字段吗?我在模型中做的事情是否可行,还是必须在控制器层做?
【问题讨论】:
标签: php validation cakephp model-view-controller cakephp-1.3