Codeigniter - form_validation回调函数错误消息

时间:2018-02-10 07:04:30

标签: php codeigniter

查看:

<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,但这是我第一次使用回调函数来检查给定生日的有效性。我测试了输入,你不能输入任何字母,但你可以超过最大长度。例如,格式应为&#39; YYYY-MM-DD&#39;你可以输入这样的东西:555555-55-55。

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

  

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

如果我要求的是不可能/错误的话,那么我只需添加min_length [10]和max_length [10],然后将其错误编辑为“无效日期&#39;”。

编辑:从我上面关于最大和最小长度的陈述中汲取灵感,我还在那里为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; }
    }

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

嘿,请尝试使用回调

$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;
    }
    else
    {
        $this->form_validation->set_message('validdate','Checks 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

答案 2 :(得分:0)

你应该这样打电话:

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