CodeIgniter Forums

Full Version: form_validation question/suggestion
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]RickP[/eluser]
Looking at the library code I see that the very first thing that is done is to check the length of $_POST and abort if the count is zero.

This of course works but I'm wondering if checking for a count < 2 would be better?

The problem I ran into was that if the form was called by a form (ie, a button) rather than a link the validation routines get run on an empty form. This means that the initial form display shows validation errors.

Whenever validation is required count($_POST) will always be at least 2, one for the submit button and one for the field to be validated.

Has this been discussed before? Am I overlooking something?

El Forum

[eluser]WanWizard[/eluser]
Form validation rules should only run after posting a form. And only the correct form.
If they run at any other time, you have a logic error in your code that needs corrected.

El Forum

[eluser]RickP[/eluser]
[quote author="WanWizard" date="1282337361"]Form validation rules should only run after posting a form.[/quote]
Correct.
Quote:And only the correct form.
How does the library know which is the correct form?
Quote:If they run at any other time, you have a logic error in your code that needs corrected.
No, I don't think so.

Using the example from the docs, make the following changes:

First, in the controller (with validation rules) change index() to edit() and add a new
Code:
function index() {
    $this->load->helper('form');
    $this->load->view('validation_test');
}

and then create a validation_test.php view:

Code:
<p>Test with a <a href="&lt;?=site_url('form/edit')?&gt;">URL</a></p>
<p>Test with a &lt;?=form_open('form/edit').form_submit('submit','Button').form_close()?&gt;</p>

If you click on the url, everything works as expected. However, if you click on the button the form displays with all the errors.

You can change the if statement in the edit function to:

Code:
if (count($_POST) < 2 || $this->form_validation->run() == FALSE)

all both the url and the button work as expected.