Reputation: 20115
I am using CodeIgniter's form validation. Here is an example:
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
The documentation say:
Any native PHP function that accepts one parameter can be used as a rule, like htmlspecialchars, trim, MD5, etc.
What if I want the value to pass through my own custom filter? For example, I would like the value to be cleaned of "badWord".
function curseWordRemove($original = '') {
return str_replace('badWord', '', $original);
}
CodeIgniter already provides ways to do custom validation, but not custom filters. The custom validation only returns true or false, not the filtered string.
function isPolite($string = '') {
if (strpos($string, 'badWord') !== false) {
$this->form_validation->set_message(
'fieldName',
'contains a very bad word'
);
return false;
} else {
return true;
}
}
Upvotes: 2
Views: 2814
Reputation: 20473
Jojo, you must have missed it the userguide, its called a callback
, and here is the documentation.
An Example:
<?php
class Form extends CI_Controller {
public function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
$this->form_validation->set_rules('password', 'Password', 'required');
$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.email]');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->view('formsuccess');
}
}
public function username_check($str)
{
if ($str == 'test')
{
$this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
return FALSE;
}
else
{
return TRUE;
}
}
}
?>
Basically, create a validation called callback_check_bad_words
and a matching function in your controller called check_bad_words($value)
. Return a boolean as a result (as the result goes back to the validation).
Since you can only pass back a boolean, you need to either use a global variable, OR run the 'sanitization' of your word later on, you don't need it in validation UNLESS you want to stop it from submission.
If your intent is to sanitize the input for bad words, just do it, don't validate for it.
Upvotes: 4