我的表单中有3个字段 - 比如A,B和C.我想将验证规则设置为如果字段A和B为空则需要C.否则,需要A和B.
我查了一些这方面的材料,基本上我发现我可以使用回调函数,但我对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;
}
}
Run Code Online (Sandbox Code Playgroud)
这很简单
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$post_data = $this->input->post();
$this->form_validation->set_rules('A', 'FieldA', 'required');
$this->form_validation->set_rules('B', 'FieldB', 'required');
if(!isset($post_data['A']) AND !isset($post_data['B']))
{
$this->form_validation->set_rules('C', 'FieldC', 'required');
}
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('success');
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6966 次 |
| 最近记录: |