Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating input before using it with CodeIgniter's Form Validation Class

Since you can't do this: $this->form_validation->set_rules($VARIABLE, 'Some text', 'required');, is it possible to do something similar to:

$variable = $this->input->post('some_input');
$variable = some_function_which_manipulates_the_input($variable);

$this->form_validation->set_rules($i_want_the_variable_here, '', '');

to manipulate the input before validation check? Adding a custom callback seems a little clumsy to me since one method could do several things (not necessarily targeted at X validation field).

like image 407
Peter Avatar asked Oct 29 '25 03:10

Peter


1 Answers

Since you can't do this: $this->form_validation->set_rules($VARIABLE, 'Some text', 'required');

You certainly can do that, as long as $VARIABLE contains the name attribute of the field you want to validate.

It looks like you're passing the actual $_POST value as the first parameter of set_rules() - it should in fact be the field name. See the section on setting rules:

http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules

$this->form_validation->set_rules();

The above function takes three parameters as input:

  • The field name - the exact name you've given the form field.
  • A "human" name for this field, which will be inserted into the error message.Names.
  • The validation rules for this form field.

If you want to alter the actual value of the input before or after validation, just add one or more "prepping" rules.

http://codeigniter.com/user_guide/libraries/form_validation.html#preppingdata

Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, MD5, etc.

Note: You will generally want to use the prepping functions after the validation rules so if there is an error, the original data will be shown in the form.

You may use the rules before as well, if you want to trim() something before validating for instance. Callbacks will work as well, they serve the same purpose as any function of the form validation library, or any vanilla php functions - validate the data by returning TRUE/FALSE, or alter the data - just note that by default, the callback must belong to the controller the validation is run in. You may use your own helper functions as well, anything that is available to the current script at the point when the data is validated.

like image 192
Wesley Murch Avatar answered Oct 31 '25 16:10

Wesley Murch



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!