2
votes

I have an e-mail field which is -not- required in my form validation. It should be able to be left blank. However, when I use the "valid_email" parameter of the form validation's set_rules, it still gives an error message that the e-mail is not valid when it's not supposed to check this if the field has not been filled out.

3
Please post your relevant code. - Sampson

3 Answers

4
votes

Rule Reference

Checking the reference on this matter tells us the following regarding the valid email rule:

Returns FALSE if the form element does not contain a valid email address.

This would be true of an empty field, as well as a field with bad values.

Trimming

I notice in the examples provided by CodeIgniter that emails are usually not only required, and required to be valid emails, but are also trimmed. This may result in a different outcome.

$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');

During the validation process, the following is considered:

// If the field is blank, but NOT required, no further tests are necessary
if ( ! in_array('required', $rules) AND is_null($postdata))

It may be the case that the contents of your email field aren't exactly null, and are therefore raising flags with the valid_email requirement.

Possible Related Bugs

Three months prior to the date of this answer there was discussion on bitbucket regarding this very topic. The discussion can be viewed at https://bitbucket.org/ellislab/codeigniter-reactor/issue/117/input-fields-are-automatically-required.

It's stated that using array-syntax (see below) in the markup results in similar errors even when the required rule is not set:

<input name="user[email]" />

Further discussion, and patches, are available here, http://codeigniter.com/forums/viewthread/159243. One suggest patch that seems to solve the issue is to replace the is_null() call with empty() in the aforementioned code:

So the following:

if ( ! in_array('required', $rules) AND is_null($postdata))

Becomes:

if ( ! in_array('required', $rules) AND empty($postdata))
1
votes

according to https://codeigniter.com/user_guide/libraries/validation.html?highlight=validation#id28

use permit_empty this

Allows the field to receive an empty array, empty string, null or false

so your code looks like this:

$this->form_validation->set_rules('email', 'Email', 'permit_empty|valid_email');
0
votes

You just have to appreciate that '' IS not a valid e-mail address. If you don't want to validate some postdata and don't care if it's empty, you shouldn't set a rule on it, like so:

if($this->input->post('item'))
{
    $this->form_validation->set_rules('item', 'Item number', 'trim|alpha_numeric|max_length[30]');
}

In this case, if there is nothing submitted for 'item', no rule is added, so the rest of the data would go on to validation stage etc. as normal.