可以同时使用内联验证规则和基于配置文件的验证规则吗?

时间:2014-02-20 01:38:32

标签: php codeigniter validation

PHP / CodeIgniter。

为了设置一个验证逻辑的表单:“需要一个或两个字段”我必须使用这样的内联表单验证(源是http://ellislab.com/forums/viewthread/136417/#672903):

if ( ! $this->input->post('email'))
{
   $this->form_validation->set_rules('phone', 'Phone Number', 'required');
}
else
{
   $this->form_validation->set_rules('phone', 'Phone Number', '');
}

// If no phone number, email is required
if ( ! $this->input->post('phone'))
{
   $this->form_validation->set_rules('email', 'Email Address', 'required|valid_email');
}
else
{
   $this->form_validation->set_rules('email', 'Email Address', 'valid_email');
} 

但我有很多其他形式,我更喜欢使用基于配置文件的表单验证。

我想不出让两者共存的方法,我现在真的不想把我的所有规则都带到代码体中。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

在您的库中创建一个名为MY_Form_validation

的文件
class MY_Form_validation extends CI_Form_validation 
{

public function __construct($rules = array())
{
   parent::__construct($rules);
   $this->CI->lang->load('MY_form_validation');
}


function email_phone($str)
{
  if(!$str)
  {   
    // if POST phone exists validate the phone entries   
    //validation for phone
    return TRUE;
  }else{
    //if no phone was entered
    //check the email
    $email = $this->input->post('email'));

    //use the systems built in validation for the email
    //set your error message here

    return $this->valid_email($email) && $this->required($email);
  }
}
}

//or set the message here
$this->form_validation->set_message('email_phone','Please enter either an email or phone.');
$this->form_validation->set_rules('phone', 'Phone Number', 'email_phone');

答案 1 :(得分:0)

您可以在同一个应用程序中使用配置文件或内联规则中的规则集。

配置/ form_validation.php

$config = array(
    'ruleset1' => array(
        array(
            'field' => 'username',
            'label' => 'Username',
            'rules' => 'required|trim|alpha'
        ),
    )
);

控制器示例

    public function ruleset()
    {
        if ($this->input->post())
        {
            // runs validation using ruleset1 from the config
            if ($this->form_validation->run('ruleset1') == FALSE)
            {
                ...
            }
        }
    }

    public function inline_rules()
    {
        if ($this->input->post())
        {
            // ignores the config and uses the inline rules
            $this->form_validation->set_rules('username', 'Username', 'required|trim|alpha_numeric');

            if ($this->form_validation->run() == FALSE)
            {
                ...
            }
        }
    }

注意:我发现尝试将它们混合为同一个表单不起作用。在同一表单上指定内联规则和规则集将导致完全忽略规则集并应用内联规则。