I have questions about my codeigniter form validation. I try to validate the input form for name so it will generate error if user using symbol like ">?<*&%^$". Here is my code:
My rules:
$this->load->library('form_validation');
$this->form_validation->set_rules('full_name', 'Name', 'trim|required|callback_name_check',
array(
'name_check' => '%s should not using symbols'
)
);
This is my callback function (I tried to modify this from the last example I saw, so I thought the problem was here)
public function password_check($str)
{
if (preg_match('#[<>?&%$##]#', $str)) {
return TRUE;
}
return FALSE;
}
I have tried another example from another StackOverflow answer to use / as delimiter (like this --> [/<>?&%$##/]), but still, doesn't work. I'll appreciate your help sensei :)
Validation should be
$this->load->library('form_validation');
$this->form_validation->set_rules('full_name', 'Name', 'trim|required|callback_name_check');
Inside call back function
public function name_check($str)
{
if (preg_match('#[<>?&%$##]#', $str)) {
{
return TRUE;
}
else
{
#adding new validation error should be
$this->form_validation->set_message('full_name', '%s should not using symbols'); # input field name should come to first
return FALSE;
}
}
Note: Didn't validate REGEX which you have posted
Related
I am trying to show validation error if single quotes are passed with the below function, but its not working out
function alpha_dash_space($str) {
return (!preg_match("/^([-a-z_ ])+$/i", $str)) ? FALSE : TRUE;
}
-
$this->form_validation->set_error_delimiters('<li class="errorlist">', '</li>')->set_rules('book_title', 'Book Title', 'trim|required|min_length[2]|max_length[150]|xss_clean|callback_alpha_dash_space');
Example:
If input provided for book_title = The Roa'r of King's
Expected validation error message should
show "Book Title has invalid character"
if "The Roar of Kings" of passed then there will be no validation error.
If you're validating form input rather use CodeIgniters own implementation. Your form validation rules should look like the below.
$this->form_validation->set_rules('username', 'Username', 'alpha_dash');
try this one
function custom_alpha_dash_spaces($str) {
if (!preg_match("/^([-a-z0-9_ -])+$/i", $str)) {
$this->form_validation->set_message('custom_alpha_dash_spaces', 'The %s can not contain quotes.');
return FALSE;
}
return true;
}
By some reason form validation doesn't call callback function which I set in the rules.
It is rules sets
if( ! empty($_POST))
{
ci()->form_validation->set_rules('login', 'Username', 'trim|required');
ci()->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback_check_email');
if (ci()->form_validation->run() == TRUE)
{
}
}
and a function
public function check_email($str)
{
ci()->load->model(array('secure_model', 'admin/members_model'));
$o['username'] = ci()->input->post('login');
$o['email'] = ci()->input->post('email');
$m = $this->_model->get_row($o);
if ( ! $m)
{
$this->form_validation->set_message('check_email', lang('unlock_incorrect_login'));
return FALSE;
}
else
{
return FALSE;
}
}
I set FALSE twice to see if it call callback function but it doesn't display error message. So I suppose CI doesn't try to call it. What is wrong?
In your check_email() function, you're using $this->form_validation instead of ci()->. I'm not sure why you're using ci() instead of the standard CI way of using $this but that's the part in your code which seems off compared to the rest.
I tried to validate the password field using a callback function. But when I use the following code, all validations do not work any more WHEN I TYPE 1234 (callback condition). When I remove the validation which contains the callback function, other validations work perfectly..
This is my validation rules
$crud->set_rules('password', 'Password', 'callback_valid_password');
$crud->set_rules('confirm_password', 'Password Confirmation', 'required|matches[password]');
$crud->set_rules('email', 'Email', 'trim|required|valid_email');
Here is my callback function
function valid_password($str) {
if ($str=="1234")
{
$crud->set_message('_valid_password', 'The field should be 1234');
//do some pw validation
return FALSE;
}
else
{
return TRUE;
}
}
Please help me to find what is wrong here.. Thank you in advance
p.s - I am using php 5.4 version with the latest grocery crud version
function valid_password($str) {
if ($str=="1234")
{
$this->form_validation->set_message('valid_password', 'The field should be 1234');
//do some pw validation
return FALSE;
}
else
{
return TRUE;
}
}
For those who are still struggling to find the solution, please follow the checklist.
Are you using CodeIgniter as MVC or HMVC?
1. HMVC
(A) - Check if you have updated the file (./application/libraries/Grocery_crud.php) as suggested below.
(B) - Before "__construct" inside " "class Grocery_CRUD extends grocery_CRUD_States" add "protected $hmvc;"
(C) - Update "__construct" with as below:
public function __construct($hmvc = null)
{
$this->hmvc = $hmvc;
}
(D) - Update "form_validation" with as below:
protected function form_validation()
{
if ($this->form_validation === null) {
$this->form_validation = new grocery_CRUD_Form_validation();
if ($this->hmvc) $this->form_validation->CI = $this->hmvc;
$ci = &get_instance();
$ci->load->library('form_validation');
$ci->form_validation = $this->form_validation;
}
return $this->form_validation;
}
(E) - Use "$crud = new Grocery_crud($this);" instead "$crud = new Grocery_crud();" in your Controller.
(F) - GC set_rules example:
$crud->set_rules("level_title", 'Level Title Label', 'trim|required|callback_unique_level_field_check');
(G) - Callback method example:
public function unique_level_field_check ($level_title)
{
if ( empty($level_title))
{
$this->form_validation->set_message('unique_level_field_check', "Level Title Label should be unique");
return FALSE;
}
return TRUE;
}
2. MVC
Follow F & G only (above).
GroceryCRUD Forum: See details here
Im carrying out some form validation with codeigniter using a custom validation callback.
$this->form_validation->set_rules('testPost', 'test', 'callback_myTest');
The callback runs in a model and works as expected if the return value is TRUE or FALSE. However the docs also say you can return a string of your choice.
For example if I have a date which is validated, but then in the same function the format of the date is changed how would I return and retrieve this new formatted value back in my controller?
Thanks for reading and appreiate the help.
I'm not entirely sure I got what you were asking, but here's an attempt.
You could define a function within the constructor that serves as the callback, and from within that function use your model. Something like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controllername extends CI_Controller {
private $processedValue;
public function index()
{
$this->form_validation->set_rules('testpost','test','callback');
if ($this->form_validation->run()) {
//validation successful
echo $this->processedValue; //outputs the value returned by the model
} else {
//validation failed
}
}
private function callback($input)
{
$this->load->model('yourmodel');
$return = $this->yourmodel->doStuff($input);
//now you have the user's input in $input
// and the returned value in $return
//do some checks and return true/false
$this->processedValue = $return;
}
}
public function myTest($data){ // as the callback made by "callback_myTest"
// Do your stuff here
if(condition failed)
{
$this->form_validation->set_message('myTest', "Your string message");
return false;
}
else
{
return true;
}
}
Please try this one.
I looked at function _execute in file Form_validation of codeigniter. It sets var $_field_data to the result of callback gets(If the result is not boolean). There is another function "set_value". Use it with the parameter which is name of your field e.g. set_value('testPost') and see if you can get the result.
The way Tank_Auth does this in a controller is like so
$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
if ($this->form_validation->run()) {
// validation ok
$this->form_validation->set_value('login')
}
Using the set_value method of form_validation is undocumented however I believe this is how they get the processed value of login after it has been trimmed and cleaned.
I don't really like the idea of having to setup a new variable to store this value directly from the custom validation function.
edit: sorry, misunderstood the question. Use a custom callback, perhaps. Or use the php $_POST collection (skipping codeigniter)...apologies haven't tested, but I hope someone can build on this...
eg:
function _is_startdate_first($str)
{
$str= do something to $str;
or
$_POST['myinput'} = do something to $str;
}
================
This is how I rename my custom callbacks:
$this->form_validation->set_message('_is_startdate_first', 'The start date must be first');
.....
Separately, here's the callback function:
function _is_startdate_first($str)
{
$startdate = new DateTime($this->input->post('startdate'), new DateTimeZone($this->tank_auth->timezone()));
$enddate = new DateTime($this->input->post('enddate'), new DateTimeZone($this->tank_auth->timezone()));
if ($startdate>$enddate) {
return false;
} else {
return true;
}
}
i am newbie in CodeIgniter...and i am trying to do form validation for array input...
the array name is pages[].
and i wrote:
$this->form_validation->set_rules('pages[]','','required');
if i use that:
$this->form_validation->set_message('required', 'you not selected pages.');
it will not change the other "required" validation input params?
So how can i set error message only for one validation?
This is my custom Form_Validation class. you can use it if you want to. put this file under your libraries directory. then you can use the set message like this:
$this->form_validation->setError(YOUR_INPUT_NAME, THE_MESSAGE);
ex: $this->form_validation->setError('email', 'Invalid email');
--
class MY_Form_validation extends CI_Form_validation {
public function set_error($field, $pesan_error){
$this->_field_data[$field]['error'] = $pesan_error;
}
public function get_error($field){
return $this->_field_data[$field]["error"];
}
public function get_all_error(){
// return $this->_field_data[$field]["error"];
$fields = $this->_field_data;
$pesan = "";
foreach($fields as $field ) {
if($field["error"]) {
$pesan .= "<p>$field[error]</p>";
}
}
return $pesan;
}
}
It doesn't work like you stated, you should read this section of the user guide more carefully.
I'm not sure I can explain better, but the first field of the set_message method doesn't refer to the type of validation but to the callback function's name, that's the function which is doing the custom validation work.
What you need to do is define your callback function (the guide has a good example), in which you iterate through your array's elements and count what's checked. If at the end of the iteration the counter is 0 you set your error message.
Hope this helps.