gpt4 book ai didi

codeigniter - 如何在 CodeIgniter 中使用表单验证为 set_rules() 编写条件?

转载 作者:行者123 更新时间:2023-12-03 10:05:27 25 4
gpt4 key购买 nike

我的表单中有 3 个字段 - 比如说 A、B 和 C。我想将验证规则设置为如果字段 A 和 B 为空则需要 C。否则,需要 A 和 B。

我查了一些关于这个的 Material ,基本上我发现我可以使用回调函数,但我对 CodeIgniter 有点陌生,我无法弄清楚写出它的语法。

最佳答案

回调是处理此问题的最简洁方法:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class YourController extends CI_Controller {

public function save()
{
//.... Your controller method called on submit

$this->load->library('form_validation');

// Build validation rules array
$validation_rules = array(
array(
'field' => 'A',
'label' => 'Field A',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'B',
'label' => 'Field B',
'rules' => 'trim|xss_clean'
),
array(
'field' => 'C',
'label' => 'Field C',
'rules' => 'trim|xss_clean|callback_required_inputs'
)
);
$this->form_validation->set_rules($validation_rules);
$valid = $this->form_validation->run();

// Handle $valid success (true) or failure (false)

}


public function required_inputs()
{
if( ! $this->input->post('A') AND ! $this->input->post('B') AND $this->input->post('C'))
{
$this->form_validation->set_message('required_inputs', 'Either A and B are required, or C.');
return FALSE;
}

return TRUE;
}
}

关于codeigniter - 如何在 CodeIgniter 中使用表单验证为 set_rules() 编写条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14464599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com