php 复选框的 CodeIgniter 表单验证规则

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16854232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:47:34  来源:igfitidea点击:

CodeIgniter form validation rules for checkbox

phpcodeigniter

提问by Mifas

I've a form with checkbox for accepting TOS. The problem is I need to add custom error for this checkbox,

我有一个带有复选框的表单,用于接受 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>

PHP

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{

}
?>

When the user does not select TOS, Then I have to say

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

Please read and accept our terms and conditions.

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

Note: I've added form_errorfunction to display individual errors

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

回答by Rikesh

I will do something like this,

我会做这样的事情,

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

}

And for custom message you can call a custom validate function like,

对于自定义消息,您可以调用自定义验证函数,例如,

$this->form_validation->set_rules('accept_terms', '...', 'callback_accept_terms');

And then set up this method in the controller:

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

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;
}

回答by Rahmatullah Darwish

you can put the value=1 and check with codeigniter like this:

你可以把 value=1 和 codeigniter 像这样检查:

<input type="checkbox" name="accept_terms" value="1" /> Accept TOS<br>
$this->form_validation->set_rules('accept_terms','TOS','trim|required|xss_clean|greater_than[0]');

]

]