views:

73

answers:

2

Hi,

What does the trim form validation rule actually do and when should I use it?

Thanks

+2  A: 

It removes whitespace from the beginning and end of an input string.

You can think of validation rules as a pipeline of routines run on the input. For example :

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

When validating the email input CodeIgniter :

  1. Removes whitespace from the beginning and end of the string
  2. Checks that the resulting string is non-empty
  3. Checks that it is a valid email address

The trim routine is normally run before other routines and placed at the front of the list.

You should use it when you want to ignore the starting and trailing whitespace in the input. Perhaps the user has accidentally typed a space character after an email address in a HTML form. The space character should not be taken as part of the email address and should be removed.

Stephen Curran
I think that it might literally use the trim() function from php. There's a few built in functions for the form_validation class (like valid_email), but I'm pretty sure you can use any function. It says in the user guide: "Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, MD5, etc."
Matthew
Thats right. Its the in-built PHP function. I probably should have mentioned that in my answer too. Thanks for adding the comment.
Stephen Curran
A: 

You can use any in-built PHP function that takes one argument and returns a value or true or false as a form validation rule. So trim isn't actually a Codeigniter specific function, it's a PHP one.

Some other in-built PHP functions you can use are; is_int (checks if a number is an integer), ltrim (trims left of a string), rtrim (trims the right of a string), sha1, md5, etc.

Dwayne