CodeIgniter表单复选框的验证规则

Mif*_*fas 2 php codeigniter

我有一个带有复选框的表单,用于接受TOS.问题是我需要为此复选框添加自定义错误,

    <form>

    <input type="text" name="fname" placeholder="Name" /><?php echo form_error('fname') ?>
    <input type="text" name="email" placeholder="Email" /><?php echo form_error('email') ?>
    <input type="text" name="password" placeholder="Password" /><?php echo form_error('password') ?>

    <input type="checkbox" name="accept_terms" value="yes" /> Accept TOS<br>
    <?php echo form_error('accept_terms') ?>

    </form>
Run Code Online (Sandbox Code Playgroud)

PHP

<?php 

 $this->form_validation->set_rules('fname','First Name','trim|required|xss_clean');
 $this->form_validation->set_rules('email','Email','trim|required|xss_clean|valid_email');
 $this->form_validation->set_rules('password','Password','trim|required|xss_clean');
 $this->form_validation->set_rules('accept_terms','TOS','trim|required|xss_clean'); // Need to add custom error message 

if ( $this->form_validation->run() === TRUE ) {

}else{

}
?>
Run Code Online (Sandbox Code Playgroud)

当用户没有选择TOS时,我不得不说

请阅读并接受我们的条款和条件.

注意:我添加form_error了显示单个错误的功能

Rik*_*esh 10

我会做这样的事,

if ($this->form_validation->run() === TRUE ) {
   if(!$this->input->post('accept_terms')){
      echo "Please read and accept our terms and conditions.";
      // Redirect
   }
}
else{

}
Run Code Online (Sandbox Code Playgroud)

对于自定义消息,您可以调用自定义验证功能,如,

$this->form_validation->set_rules('accept_terms', '...', 'callback_accept_terms');
Run Code Online (Sandbox Code Playgroud)

然后在控制器中设置此方法:

function accept_terms() {
    if (isset($_POST['accept_terms'])) return true;
    $this->form_validation->set_message('accept_terms', 'Please read and accept our terms and conditions.');
    return false;
}
Run Code Online (Sandbox Code Playgroud)

  • 您可能希望将`accept_terms()`函数`_accept_terms()`和`callback_accept_terms`重命名为`callback__accept_terms`,否则可以通过浏览器@ http://sample.com/controler/accept_terms任意访问accept_terms方法.以下划线开头的函数对公共访问是隐藏的. (2认同)