Reputation: 107
I have a html form to save projects in cakephp. i want to restrict the user to save same project name. If any body type the same project name for that i applied the 'unique' validation in model but if anybody enter the same name with spaces before or after the project name it accepts it and store into the database.THat is the issue. I want to remove that extra spaces before save.
Please help.
Upvotes: 2
Views: 6952
Reputation: 722
Through my research, I think the best solution if your data is in array format then try this => Stackoverflow: How to trim white spaces of array values in php
While, if your data is not an array then you can simply use:
$data = trim($data);
Upvotes: 0
Reputation: 1070
The best place to remove whitespace from user input i.e. trim()
is in the beforeFilter()
callback at the Controller level. For PHP5+ the array function array_walk_recursive()
makes this job very easy.
For example:
public function beforeFilter()
{
parent::beforeFilter();
// remove leading and trailing whitespace from posted data
if (!function_exists('trimItem')) {
function trimItem(&$item,$key){
if (is_string($item)){
$item = trim($item);
}
}
}
array_walk_recursive($this->request->data, 'trimItem');
}
Drop this code into AppController
and user input will be trimmed on all forms
Hope this helps
Upvotes: 8
Reputation: 4856
Just as an addition to @Prasantn Bebdra's answer and since the asker doesn't know where and how to use trim()
.
To trim all the data that is comming from POST in your controller (just before the call to Model->save()
) do:
foreach ($this->data as $key => $value) {
$this->data[$key] = trim($value);
}
You can also use this in the Model
by utilizing one of it's callbacks for example beforeValidate() or beforeSave() where in your case it should be better to use beforeValidate since you'd probably also want to validate this data afterwards.
You should also notify the user that the input will be trimmed and maybe also do such trimming on the client-side (before the POST) - check this StackOverflow answer out.
Upvotes: 3
Reputation: 32750
use trim
which will trim your string from both sides
ref : http://php.net/manual/en/function.trim.php
trim($str);
Upvotes: 3