Submitting form to itself and echoing validation errors in CodeIgniter

Zanshin13

I had few forms in my project, they were submitted to public function's like site.com/email => site.com/validate_email, but then I realized that that's not what I want. Now I need to make them submit to themselfs ,check and display validation errors. What is the appropriate way to do this? Check for emptyness of $_POST and then call my new _validate_email(//that will return true or false) if post isn't empty? Or something else not that noobish?:)

for example:

public function login()
{
        $this->load->view('login');
}


public function login_validation()
{
        $this->load->library('form_validation');

        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim|xss_clean|callback_validate_credentials');
        $this->form_validation->set_rules('password','Password','required|md5');

        if($this->form_validation->run())
        {
            //some stuff here
        }
        else
        {
            $this->load->view('login'); //or redirect()?
        } 

view:

<?php $this->load->view('header'); ?>


<div class="form-container">
    <?=$this->form_validation->validation_errors();?>
    <?php
    $form_atr = array(
        'id' => 'form-set'
    );
    echo form_open('main/login_validation', $form_atr);//this should be 'main/login'
    ?>
    <div class="header">
        /*
here goes other parts of form
*/
</div><!--END  form-container -->`
<?php $this->load->view('footer'); ?>

So, basicaly i need to combine login() and login_validation(), but make it so that when user`s input incorrect i get reloaded page of the same view with the same URL and get validation errors displayed.

I've tried to put code of validation into the same function that displays form, but I can't figure out how to redirect or reload the view to show val.errors if any.

Zanshin13

So, I think this way is correct(It really should be):

I made my login_validation() private by adding '_' before it, like so _login_validation() Than I added an if() statement that contains $_POST form variables and i am cheking them with php isset() function, that way the code can determine when user submitted a form. And after all that I just call _login_validation() if inputs are set or load again my login view if not.

public function login()
{

    if(isset($_POST['password']) && isset($_POST['email']))
    {
        $this->_login_validation();
    }
    else
    {
        $this->load->view('login');
    }
}

and dont forget to process your form so it would submit to the same URL:

echo form_open('', $form_atr);

Hope that will help someone someday.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related