在发布包含名为“id”和“url”的两个字段的表单后,我有以下代码:
$this->load->library('form_validation');
$this->form_validation->set_rules('id', 'id', 'trim|xss_clean');
$this->form_validation->set_rules('url', 'url|id', 'trim|xss_clean|callback_url_check');
db查询需要两个字段。
调用函数url_check($ str,$ id),但在这种情况下,'id'的值始终为0。
如果我这样做:
$this->form_validation->set_rules('url', 'url', 'trim|xss_clean|callback_url_check');
并致电url_check($str)
所有内容都按照预期的方式运行。
问题是如何将两个值传递给url_check($str, $id)
?
答案 0 :(得分:41)
您可以直接使用$ this-> input-> post:
function check_url() {
$url = $this->input->post('url');
$id = $this->input->post('id');
// do some database things you need to do e.g.
if ($url_check = $this->user_model->check_url($url, $id) {
return TRUE;
}
$this->form_validation->set_message('Url check is invalid');
return FALSE;
}
答案 1 :(得分:32)
按照in the docs描述的正确方式(至少对于CI 2.1+):
$this->form_validation->set_rules('uri', 'URI', 'callback_check_uri['.$this->input->post('id').']');
// Later:
function check_uri($field, $id){
// your callback code here
}
答案 2 :(得分:8)
这似乎也有效。
$id = 1;
$this->form_validation->set_rules('username', 'Human Username', 'callback_username_check['.$id.']');
function username_check($str, $id) {
echo $id;
if ($str == 'test') {
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
return FALSE;
}
else {
return TRUE;
}
}
答案 3 :(得分:2)
如果我正确理解form_validation,则每个规则(set_rules)都适用于表单的一个字段,而您的回调只会检查一个字段。在你的情况下,似乎'id'超出了范围。相反,可以将数组传递给set_rules函数并执行回调。我还没试过这个。 http://codeigniter.com/user_guide/libraries/form_validation.html#validationrulesasarray
答案 4 :(得分:1)
关于使用其他答案中建议的回调参数的说明。如果您使用app/config/form_validation.php
创建验证规则,则$this->input->post('parameter')
语法将无法工作,因为该对象在执行中读取该文件内容时的CI Loader中不可用。你必须在你的回调例程中进行调用,例如:
public function _validate_user_signup($username, $password) {
$var = $this->input->post('password');
在这种情况下,传递给方法的第二个参数不包含密码,但是在调用之后会有$ var。
我希望这很清楚。 马特
答案 5 :(得分:0)
最好使用表单验证库来获取正在验证的数据。
并非总是您的数据位于$ _GET或$ _POST中(请参阅https://www.codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post)。
您可以在验证回调中访问数据的最佳方法是:
$this->form_validation->validation_data
" validation_data"是CI_Form_validation类中的公共属性。