【问题标题】:Codeigniter - form_validation callback function error messageCodeigniter - form_validation 回调函数错误信息
【发布时间】:2020-04-22 14:10:30
【问题描述】:

查看:

<div class="container">
    <div class="row">
        <div class="col-md-3">
        </div>
        <div class="col-md-6">
        <form method="post" action="<?php echo base_url();?>account/register">
        <?php $form_error = $this->session->flashdata('error'); ?>
          <div class="form-group">
            <label for="username">Username</label>
            <input class="form-control" id="username" name="username" type="input">
            <div id="form_error"><?php echo $form_error['username']; ?></div>
          </div>
          <div class="form-group">
            <label for="password">Password</label>
            <input class="form-control" id="password" name="password" type="password">
            <div id="form_error"><?php echo $form_error['password']; ?></div>
          </div>
          <div class="form-group">
            <label for="confirm_password">Confirm Password</label>
            <input class="form-control" id="confirm_password" name="confirm_password" type="password">
          <div id="form_error"><?php echo $form_error['confirm_password']; ?></div>
          </div>
          <div class="form-group">
            <label for="gender">Gender</label>
            <select class="form-control" id="gender" name="gender">
                <option disabled selected value="">select a gender</option>
                <option value="Male">Male</option>
                <option value="Female">Female</option>
                <option value="Other">Other</option>
            </select>
            <div id="form_error"><?php echo $form_error['gender']; ?></div>
          </div>
          <div class="form-group">
            <label for="birthdate">Birthdate</label>
            <input class="form-control" id="birthdate" name="birthdate" type="date">
            <div id="form_error"><?php echo $form_error['birthdate']; ?></div>
          </div>



          <button type="submit" class="btn btn-primary btn-block">Submit</button>
        </form>
        <div class="text-center">
        <a class="d-block small mt-3" href="<?php echo base_url();?>pages/login_user">Already have an account?</a>
        </div>
        </div>
        <div class="col-md-3">
        </div>
    </div>
</div>
</body>

账户管理员:

public function register(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
$this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date');

if($this->form_validation->run() == FALSE){
$form_error = array('username' => form_error('username'),
        'password' => form_error('password'),
        'confirm_password' => form_error('confirm_password'),
        'gender' => form_error('gender'),
        'birthdate' => form_error('birthdate'));
$this->session->set_flashdata('error', $form_error);
redirect('pages/register_user');
}else{ 
$data = array('username' => $this->input->post('username'),
            'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
            'gender' => $this->input->post('gender'),
            'birthdate' => $this->input->post('birthdate'),
            'date_created' => mdate('%Y-%m-%d',time()),
            'last_login' => mdate('%Y-%m-%d',time()));
if($this->account_model->create_account($data)){
$this->session->set_flashdata('message','Registration Successful');
redirect('pages/login_user');
}else{
$this->session->set_flashdata('message','Registration Failed');
redirect('pages/register_user');}}
}

//form_validation callback
public function valid_date($birthdate){
    echo 'aw';
if(date('YYYY-MM-DD',strtotime($birthdate))){
return TRUE; }else{
    echo $birthdate;
$this->form_validation->set_message('valid_date', 'Invalid Birthdate');
$form_error['birthdate'] = form_error('valid_date');
$this->session->set_flashdata('error',$form_error);
return FALSE; }
}

页面控制器:

public function login_user(){
    $data['title'] = 'Login';
    $this->load->view('template/header',$data);
    $this->load->view('template/navbar');
    $this->load->view('pages/login');
    $this->load->view('template/footer');
    }

    public function register_user(){
    $data['title'] = 'Register';
    $this->load->view('template/header',$data);
    $this->load->view('template/navbar');
    $this->load->view('pages/registration');
    $this->load->view('template/footer');
    }

我尝试在回调函数中设置 flashdata,但这是我第一次使用回调函数来检查给定生日的有效性。我测试了输入,你不能输入任何字母,但你可以超过最大长度。例如格式应该是 'YYYY-MM-DD' 你可以输入这样的内容:555555-55-55。

我的所有其他错误都成功打印,但 valid_date 回调函数打印错误:

无法访问与您的字段名称对应的错误消息 生日。(有效日期)

如果我要求的是不可能/错误的,那么我将添加一个 min_length[10] 和 max_length[10] 并将其错误编辑为“无效日期”。

编辑:从我上面关于最大和最小长度的陈述中获得灵感,我还在那里为 valid_date 添加了一个自定义错误,你知道它有什么作用。

这是我更新的控制器:

public function register(){
    $this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
    $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
    $this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
    $this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|valid_date',
    array('valid_date' => 'Invalid Date of birth'));

    if($this->form_validation->run() == FALSE){
    $form_error = array('username' => form_error('username'),
            'password' => form_error('password'),
            'confirm_password' => form_error('confirm_password'),
            'gender' => form_error('gender'),
            'birthdate' => form_error('birthdate'));
    $this->session->set_flashdata('error', $form_error);
    redirect('pages/register_user');
    }else{ 
    $data = array('username' => $this->input->post('username'),
                'password' => password_hash($this->input->post('password'),PASSWORD_BCRYPT),
                'gender' => $this->input->post('gender'),
                'birthdate' => $this->input->post('birthdate'),
                'date_created' => mdate('%Y-%m-%d',time()),
                'last_login' => mdate('%Y-%m-%d',time()));
    if($this->account_model->create_account($data)){
    $this->session->set_flashdata('message','Registration Successful');
    redirect('pages/login_user');
    }else{
    $this->session->set_flashdata('message','Registration Failed');
    redirect('pages/register_user');}}
    }

    //form_validation callback
    public function valid_date($birthdate){
    if(date('YYYY-MM-DD',strtotime($birthdate))){
    return TRUE; }else{return FALSE; }
    }

我仍然不确定它是否真的有效或只是侥幸。

【问题讨论】:

  • 通常只在 set_message() 未定义或未直接引用函数名称时看到该消息。诡异的。你为什么在回调中这样做?没有意义...回调应该只返回不定义任何其他应用程序逻辑。
  • 我也不确定您检查日期是否有效的方法。试试这个:stackoverflow.com/questions/19271381/…
  • 我使用的方法是来自codeigniter的日期助手。如果它是有效的日期格式,那么它将转换,如果不是,那么它是无效的。我尝试在回调中设置消息,因为这就是我看到的大多数回调示例的方式,所以我从来没有想过只是在 set_rules() 第 4 个参数中简单地覆盖它。
  • 确实设置消息的方式也是我这样做的方式,但我在那里引用了会话消息。很高兴您找到了解决方案,但仍然不确定为什么 set_message() 不起作用:codeigniter.com/user_guide/libraries/…
  • 我现在的问题是我的回调函数是否正确。我似乎无法访问我的回调。我已经在其中回显了一些内容,并且我已经评论了(//)我加载视图的代码。即使日期正确,我也会不断收到无效日期,但如果我无法访问我的回调 T_T,我将无法解决此问题

标签: php codeigniter


【解决方案1】:

注册码:

public function register() {
    $this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]');
    $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|max_length[20]');
    $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
    $this->form_validation->set_rules('gender', 'Gender', 'trim|required|in_list[Male,Female,Other]');
    $this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');

    if ($this->form_validation->run() == FALSE) {
        // let's see what's going on under the hood...
        print_r($this->form_validation->error_array());
        exit;
        $form_error = array('username' => form_error('username'),
            'password' => form_error('password'),
            'confirm_password' => form_error('confirm_password'),
            'gender' => form_error('gender'),
            'birthdate' => form_error('birthdate'));
        $this->session->set_flashdata('error', $form_error);
        redirect('pages/register_user');
    } else {
        $data = array('username' => $this->input->post('username'),
            'password' => password_hash($this->input->post('password'), PASSWORD_BCRYPT),
            'gender' => $this->input->post('gender'),
            'birthdate' => $this->input->post('birthdate'),
            'date_created' => mdate('%Y-%m-%d', time()),
            'last_login' => mdate('%Y-%m-%d', time()));
        if ($this->account_model->create_account($data)) {
            $this->session->set_flashdata('message', 'Registration Successful');
            redirect('pages/login_user');
        } else {
            $this->session->set_flashdata('message', 'Registration Failed');
            redirect('pages/register_user');
        }
    }
}

引用回调需要通过callback_func_name 调用函数。

修改后的回调:

注意:项目callback_开头

参见:Correctly determine if date string is a valid date in that format(阅读:测试用例)

public function valid_date($date) {
    $format = 'Y-m-d';
    $d = DateTime::createFromFormat($format, $date);
    if ($d && $d->format($format) == $date) {
        return TRUE;
    } else {
        $this->form_validation->set_message('valid_date', 'Invalid Birthdate.');
        return FALSE;
    }
}

执行date('YYYY-MM-DD') 是错误的,因为它会产生:2018201820182018-FebFeb-SatSat。见date docs

【讨论】:

  • 这不是只检查格式是否有效而不是日期本身吗?我正在阅读 checkdate() 的 php 手册。它检查日期是否有效。
  • 如果日期确实存在?它这样做2018-01-32 产生无效。无论如何,回调是否有效?如果您在生日字段中输入2018-01-02,它是否有效?如果你输入blah,它会给你Invalid Birthdate我在上面的控制器中打印的error_array吗?
  • 公共函数valid_date(){ $birthdate = '2001-02-29'; $temp = explode('-',$birthdate); $年 = $temp[0]; $月 = $temp[1]; $day = $temp[2]; if(checkdate($month,$day,$year)){ echo 'valid';} else{ echo 'invalid';} } 如果我输入 2001-02-29 日期不存在所以它打印无效但如果我尝试向年份添加更多数字,例如 20011 它将打印有效。我很混乱。例如,如果年份是这样的: $birthdate = '20012-02-26';它仍然会打印有效。
  • 啊,我忘了重读手册,上面写着:年份介于 1 和 32767 之间。我想我在这 4 位数的年份里太投入了。
  • 我从未听说过或使用过该功能,所以我不能说。 DateTime 较新,所以我不会碰旧的东西。当您对该方法的回答超过 260 次时,我倾向于使用它。
【解决方案2】:

你应该这样称呼:

$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_valid_date');

【讨论】:

  • 我已经把我的代码改成了那个。我没有更新这个问题,因为它已经被回答了。很抱歉造成混乱。
【解决方案3】:

嘿试试这个使用回调

$this->form_validation->set_rules('birthdate', 'Birthdate', 'trim|required|callback_validdate',

//form_validation callback
public function validdate($birthdate){

    $birthdate = $this->input->post('birthdate');

    if( date('YYYY-MM-DD',strtotime($birthdate)) )
    {
        return true;
    }

    $this->form_validation->set_message('validdate','Check the birthday input to match a format like this YYYY-MM-DD');
    return false;

}

回调:您自己的验证方法

验证系统支持回调您自己的验证方法。这允许您扩展验证类以满足您的需要。例如,如果您需要运行数据库查询以查看用户是否选择了唯一的用户名,您可以创建一个回调方法来执行此操作

更多详情请阅读https://codeigniter.com/user_guide/libraries/form_validation.html#callbacks-your-own-validation-methods

【讨论】:

  • 这行不通...您的回调甚至不是函数的正确名称,也没有使用set_message()
  • @Alex 你知道回调函数及其工作原理吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-22
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 2011-11-14
  • 1970-01-01
相关资源
最近更新 更多