• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with validation and 'trim'

#1
I'm using the validation library to validate the input received from an ajax request. I'm working through the tutorial, but converting to ajax, and moving the validations into the model. My validation rules look something like this:

PHP Code:
$validation->setRules([
            'title' => [
                'label' => 'Title',
                'rules' => 'trim|required|min_length[3]|max_length[128]'
            ],
            'body' => [
                'label' => 'Body',
                'rules' => 'trim|required|min_length[3]|max_length[65535]'
            ]
        ]); 

My validation is being run on an associative array of form elements grabbed from the ajax request:
PHP Code:
$validation->run($fields); 

This is generally working well, except for the trim. Leading and trailing spaces are being saved in the DB, and also leading spaces are being counted towards the string length, rendering the min_length[3] check as useless.

I can fix this by trimming all the inputs before running them through the validation rules, but my understanding was that the validation library was capable of doing this?
Reply

#2
@Fido L Dido,

Are you sure that the trim is working properly as a rule? Have you printed it out? You could also remove trim() from the rules and add it to the sql statement to trim the value before insert/updating the database.
Reply

#3
(02-19-2020, 01:16 PM)php_rocs Wrote: @Fido L Dido,

Are you sure that the trim is working properly as a rule?  Have you printed it out? You could also remove trim() from the rules and add it to the sql statement to trim the value before insert/updating the database.

It appears to me that none of the rules are able to alter the data it is validating, which would explain why 'trim' isn't doing anything but the other rules work fine. I shall resort to trimming the input data before validating which should address the issue. I may look to see if it is possible to create a custom rule that works with a reference to the data meaning that, in theory, it should be able to be modified.
Reply

#4
As you have find out, validation don't alter your data in any way. It just checks that it's correct according to your rules.
You should alter your data before inserting them in the DB, not before validation (as it checks post and not variables).
Reply

#5
If you check the validation rules in the CodeIgniter Users Guide there is no trim rule.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.