HI guys,
I building an app using CodeIgniter and I came to a problem. I have a form with a textarea in which the user puts his text using a simple editor powered by jwysiwyg.jquery. The problem is that is need to clean this input of garbage code (link the one that comes with pasting directly from Word).
The form is validated with the form_validation library from CodeIgniter, with this rule:
array(
'field' => 'job[description]',
'label' => 'Description',
'rules' => 'trim|required|callback_clean_html'
),
Then I have a clean_html method that simply does a:
return strip_tags($text,'<a><p><br><strong><em><h3><h4><h5><ul><ol><li>');
The problem is that this is simply ignored and the original text gets inserted in the database. The method runs (I've tested). I asume it's because a callback should return TRUE or FALSE, but then xss_clean doesn't return a BOOL. The documentation isn't much help.
Any thoughs?
Thanks in advance.
I think form_validation callbacks do need to return a bool. I find that form_validation is most useful when you need to display an error message to a user usually to resubmit the form. Although the prepping functions can be convenient, they don't need to be there to validate. Why not pass the submitted string through the strip_tags function after the form is submitted but before you send it to your db?
Have you tried removing callback_ in the rule? You can do regular PHP functions like trim so this should work.
Something aI always do just to be double safe, after setting the rules for the input I also run them through this
`$string = filter_var($string, FILTER_SANITIZE_STRING);`
That will strip out the html
I too have run into situations lately where the input totally ignores the rules that have been set.
xss_clean and other CI validation functions return non-bool values. I just tested the following callback function in CI version 1.7.2:
function test_string_change($str)
{
return "$str **";
}
The string was changed successfully using callback_test_string_change. I know there were some issues with the callback functions in 1.7.0, are you using the latest version?
From what you posted, it should work. Both the "callback_" prefix and the return are correct. Validation methods can return non-bools, which will replace the value. Check the form_validation documentation, it explicitly says that.
So your problem must be in some place of the code that you didn't post.
Related
I have a question about enabling the is_unique() rule for form validation in CodeIgniter.
In another explanation (link), they don't include the model query builder for standard usage of is_unique()
I need to use the rule is_unique(table.field) for my id field.
What should I do for making this function work on my model file to initiate table.field from my database? Because at documentation, I didn't see an explanation for enabling the is_unique rule.
My current code is still use matching data manually, but I need to know how to use this rules
$this->form_validation->set_rules('siteid', 'Site ID', 'trim|required|max_length[100]|is_unique[site_tower.site_id_tlp]');
I have just gone through the link you posted, There are 2 ways to use such validation. If you have set in your configuration files.
With that you can use the code as is is_unique[TABLE_NAME.FIELD] and it will work automatically. But at times this logic might not necessarily meet your need and you will need something more complex.
For example lets say you have a members registration that requires you to check if the email already exists, you can run is_unique and it will work perfectly. Now let's say you want to edit the same member, running is_unique on an edit function will render the user unable to save the data if no data is edited. WHY? because is_unique would determine that the email is already registered although it belongs to the current user that is being edited.
How do we fix this? We run our own callback in which we specify the logic.
You do it by specifying a method within the controller (or a model -- slightly different) but you prefix the method name with callback_ so that it is detected.
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
This will then look for a method in your controller called 'username_check'
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The {field} field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
Of course you can use a query within the callback to check against the db rather than check for just a string as it shows in the example.
more information can be found on Ci3 documentation.
LINK
Use CTRL + F and search for callback or is_unique
You might have missed this?
$this->load->library('database');
works instantly after adding database lib.
I've a standard form (without object) and I need to check if field1 < field2. If not I would like to display the error in the form like I do when I'm using form validation with object.
I red http://symfony.com/doc/current/book/validation.html#validating-values-and-arrays but it's for assert constraints. Mine is specific.
I also red this http://symfony.com/doc/current/book/forms.html#adding-validation. But once again, it use constraint validation.
Maybe I need to use this : http://symfony.com/doc/current/cookbook/validation/custom_constraint.html.
Thanks for your advices
After some research, here is my solution.
In my controller, If my condition is true, than I'm using the code to set an error and return the form. That's way, I see my error for the specific field.
use Symfony\Component\Form\FormError;
...
$form = $this->createForm(new formType());
$form->get('my-field')->addError(new FormError($this->get('translator')->trans('error.message.greather.than')));
return $this->render('MyBundle:Default:search.html.twig', array('form' => $form->createView()));
I'm not sure that it's the best way but it works for me.
I'm using CodeIgniter's form validation, and I've spent a lot of time trying to fix this, with no luck.
I have this field:
<input type="text" name="user" id="user" length="20" placeholder="Username">
And I'm using this to validate:
$this->form_validation->set_rules('user', 'Username', 'trim|required|min_length[3]|max_length[20]|alpha_dash|is_unique[users.user]');
My db has a table users and user is a field in it, so I don't know what I'm doing wrong, or what the problem is. The table is empty (but I've also tried with it having records) and in phpmyadmin the "unique" icon is selected.
I know the db connection is working fine, because if I remove that rule and enter otherwise valid data and submit the form, then the user is added to the database.
Unless is_unique uses another db configuration file that I haven't configured? I don't really know. It's kind of frustrating and I'm thinking that I may as well just drop the use of a framework...
Your help would be great! Thanks.
This might/might not help: You seem to be loading the DB after running the form validation. There's also a typo uses.user.
In Transact-SQL the word "USER" is a special word. Try surrounding uses.user with a back-ticks like so: `users.user`...see if that helps.
try this :-
$this->form_validation->set_rules('user', 'Username', 'trim|required|min_length[3]|max_length[20]|alpha_dash|unique[users.user]');
it needs to load database.
$this->load->database();
I know your question is very old but I just recently encountered a similar problem with a custom form validation and after some serious debugging I found a cause and workaround.
Apparently, the CI core has a small bug: the database library isn't instanced (at least in the latest versions of CI) when calling the is_unique form validation method, thus preventing the check from actually being performed and always returning false as the validation result.
Here is the workaround for the form validation library (system/libraries/Form_validation.php)
public function is_unique($str, $field)
{
sscanf($field, '%[^.].%[^.]', $table, $field);
// add the following line
$this->CI->load->database();
return isset($this->CI->db)
? ($this->CI->db->limit(1)->get_where($table, array($field => $str))->num_rows() === 0)
: FALSE;
}
By adding the line after the comment, you'll make sure the database library is correctly instanced for the is_unique method and you'll get it to work. Without that line, the isset($this->CI->db) check will always return false
You could also put that line in the library's constructor, but then you'd be instancing the database library in all form validation rules which is not necessary (only is_unique needs it).
Using your code as an example, the is_unique validation rule works by looking for a field called user_name in your users database table. If the field with the same value exists it validates as false.
To make sure it runs only when the user submits a new value, you could check the posted value $this->input->post('user_name') against the value you pulled from the database to populate your form with. If they are the same, don't validate is_unique:
if($this->input->post('user_name') != $original_value) {
$is_unique = '|is_unique[users.user_name]'
} else {
$is_unique = ''
}
$this->form_validation->set_rules('user_name', 'User Name', 'required|trim|xss_clean'.$is_unique);
I have a helper method that returns a captcha image url & stores a session of the key:
function captcha(){
$builder = new CaptchaBuilder;
$builder->build();
Session::put('phrase', $builder->getPhrase());
return $builder->inline();
}
The user then writes the captcha and submits the form and my controller grabs all and validates it:
'captcha' => 'required|same:'.Session::get('phrase')
The problem is no-matter what it always says they phrase & the textbox submission are not the same...
I can give more information if needed, also if this is not the best way to do it please give me suggestions, I am just learning Laravel4.
Edit for some output info:
If I return the values from the controller:
return "Session:".Session::get('phrase')." - Input:".$input['captcha'];
It returns: Session:5zij5 - Input:5zij5
According to Laravel's docs, same refers to another input.
I'd recommend using a custom validation rule to compare the session and the input.
Hi I'm trying to make my own Form validator just like the authenticate method in the LoginForm that is generated on the default configs.
public function rules()
{
return array(
// username and password are required
array('mnemonic, target_reg, source_reg', 'required'),
// rememberMe needs to be a boolean
array('target_reg_indirection, source_reg_indirection', 'boolean'),
array('mnemonic','foo'),
);
}
and here is the validator method:
public function foo($attribute,$params){
$this->addError('mnemonic', 'there was an error, you foo!');
}
it just doesn't work for me... notice how I added a rule that should not-work everytime. I just made it so I could see how it worked. But I never get to see the error message in my view. The default validators (like the one that checks for required fields) work.
Any ideas?
Because not all validators map to a client-side validator.
IN addition to that, I've created the code to handle ajax form validation and I've enabled ajaxValidation in my CActiveForm.
So now all works great. The validator I've created is working via ajax validation.
I had the same problem, in my case wasn't to enabled ajaxValidation, but the "safe" validator and a mix of other things.
Here I post some reading that helped me to solve the problem. Hope this will help others with the same problem.
I read a little bit about "safe" validator. (http://www.yiiframework.com/wiki/161/understanding-safe-validation-rules/)
I Understand the difference between AjaxValidation and ClientValidation. (http://www.yiiframework.com/doc/api/1.1/CActiveForm)
I created my own validator class. (search "custom validation yii" on google).