Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding form validation enforced checks on non-required fields in CodeIgniter

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.

like image 944
Masha Avatar asked Jul 24 '26 23:07

Masha


1 Answers

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))
like image 166
Sampson Avatar answered Jul 28 '26 15:07

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!