After abusing Google for over an hour, I've found no answers to this question :
When using form_validation.php to your validation rules, Is it possible to pass a dynamic value to the callbacks?
array(
'field' => 'passwordrepeat',
'label' => 'סיסמא חוזרת',
'rules' => 'passwordsMatch['myDynamicValue']'
),
This clearly doesn't work as it passes "myDynamicValue" as a string.
Now, because this config file is loaded so early, this only available resource in it is CI_Loader, which doesn't help much, So I can't access the input class.
So my question:
Can a dynamic value pass to the config file, Or should that rule be written inline in the controller itself?
$this->form_validation->set_rules('password1', 'Password', 'trim|required|matches[password2]');
$this->form_validation->set_rules('password2', 'Verify Password', 'trim|required');
This is what I have for setting form validation on two passwords. This is what is what comes after you set all of your rules
if ($this->form_validation->run() == FALSE)
{
//Validation failed
}
else
{
//Validation suceeded carry on
}
Here is a link to some documentation
http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#validationrules
The answer to this question is a bit embarrassing.
The solution to this is that you can pass other field names to your callbacks.
However, remember that what you're passing is the field and not the actual value.
To get the actual value you'll need to access it through $_POST['field'].
For example the built in Matches function
public function matches($str, $field)
{
if ( ! isset($_POST[$field]))
{
return FALSE;
}
$field = $_POST[$field];
return ($str !== $field) ? FALSE : TRUE;
}
I feel a bit silly :)
The answer to the question is little tricky but it's easy to understand.
The solution for the asked question is here.
Create a form_validation.php file under the application/config/folder.
and past the code as bellow.
$config = array(
array(
'field' => 'passwordrepeat',
'label' => 'סיסמא חוזרת',
'rules' => 'passwordsMatch['myDynamicValue']'
),
);
the rules will loaded automatically available to the $this->form_validation->run(); this method.
Also you can append more array, I mean more rules for the different controller.
Hope this will help you.
Related
I'm facing a problem while working on file validation in Codeigniter 4. Codes are given below.
Codes in the validation file are:
public $image = [
'image_path' => [
'label' => 'Image',
'rules' => 'uploaded[image_path]|is_image[image_path]|max_size[image_path, 1024]|mime_in[image_path,image/jpg,image/jpeg,image/png]'
]
];
And, codes in the controller are:
if($image->isValid() && !$image->hasMoved()):
if(!$this->validation->run($image, "image")):
$this->session->setFlashdata('image_errors', $this->validation->getErrors() ?? "");
return redirect()->back()->withInput();
endif;
endif;
But whenever I'm trying to run these code, the following error happened:
Argument 1 passed to CodeIgniter\Validation\Validation::run() must be of the type array or null, object given.
Please suggest me possible solution for this.
Thank you.
When we need to validate form in the controller we follow this steps:
use validate() method instead of using $validation property
see Controller Validate Data
set flashdata within recirect()->with() method
see Common functions
if condition syntax should be with brackets { }, use if else endif in view files only (optional).
see Alternate Syntax
It's very important and recommended to read User Guide
if ($image->isValid() && ! $image->hasMoved())
{
if (! $this->validate('image'))
{
return redirect()->back()->withInput()->with('image_errors', $this->validator->getErrors())
}
}
if you want to use validation class just do this
if ($image->isValid() && ! $image->hasMoved())
{
$this->validation->setRuleGroup('image');
if (! $this->validation->withRequest($this->request)->run())
{
return redirect()->back()->withInput()->with('image_errors', $this->validation->getErrors())
}
}
I hope it will work fine with your code.
this is my form_validation.php
$config = array(
'buy' =>array(
array(
'field' => 'id',
'label' => 'Item',
'rules' => 'trim|required'
),
array(
'field' => 'qty',
'label' => 'Quantity',
'rules' => 'trim|greater_than[0]|callback_validate_qty'
)
)
);
My Controller to load form validation :
$this->load->library('form_validation');
Function validate_qty($qty)
$item_id = $this->input->post('id');
$total_item= $this->item_model->getTotalItem($item_id);
if ($qty >= $total_item) {
$this->form_validation->set_message('validate_qty', 'Cant Buy More than maximum stock!');
return FALSE;
}
this validation is work perfectly, but someone has got throught it, he buy more than maximum stock..
How to prevent this? I don't know how he does that, but it looks like the validation didn't work for him. When I tested, it works perfectly, I don't know what's wrong with it, maybe he uses software or anything? is there any solution? Thanks
i think your code is correct.
i have one doubt on that code.
check the variable you used in if condition is correct or not ($qty). becuase you not show the full code.i don't known how that variable comes.
Also change the code like if and else condition.
if ($qty >= $total_item) {
$this->form_validation->set_message('validate_qty', 'Cant Buy More than maximum stock!');
return false;
} else {
return true;
}
Assume if you have 30 stock in your hand and you want to get all 30 stocks out. But according to your if condition (if ($qty >= $total_item) {) it throws error.
Fix 1
if should be > (if ($qty > $total_item) {).
Fix 2
Typo - in your callback function you've used two underscores _. Get rid of one
callback__validate_qty
^^
Read more about codeigniter.com - Callbacks
I know this is a stupid question but after messing around, I am confused what is the right way of doing.
Below are my code :
View registration_form.php :
$input_data = array(
'name' => 'user_name',
'id' => 'user_name',
'value' => set_value('user_name'),
'maxlength' => MAX_CHARS_4_USERNAME
);
Controller register.php:
$this->load->model('user_model');
$this->user_model->create_user( 'customer', array() );
Form Validation Config :
$config['customer_creation_rules'] = array(
array(
'field' => 'user_name',
'label' => 'USERNAME',
'rules' => 'trim|required|alpha|strtolower'
)
);
Model user_model.php :
public function create_user( $role, $insert_array = array() )
{
// The form validation class doesn't allow for multiple config files, so we do it the old fashion way
$this->config->load( 'form_validation/administration/create_user/create_' . $role, TRUE );
$this->validation_rules = config_item( $role . '_creation_rules' );
$form_username = $this->config->item($role . '_creation_rules', 'field');
echo $form_username;
}
What I want to do right now is to check the username that the user input and auto add a number to the input username before inserting into database.
Initially I thought of getting the inputted username from the Form Validation, after messing around, I can't get the value no matter what I have tried.
Am I doing it wrongly? Do I just get from $_POST instead?
Hope you guys can help me out on this. Thanks in advance!
This shows the full list (waaaay at the bottom): http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
I don't see that one there, but it says you can use any PHP function that requires only one parameter so that should work, but you'll have to look deeper into the docs to figure out why it isn't.
I don't think you can set rules for a form, you have to set them per variable, as the docs show:
$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]');
So the framework is CodeIgniter 2.0.2. I have a form that has groups of fields that correspond to rows in a database. The names of the fields are in the format:
opt[0][foo]
opt[0][bar]
opt[1][foo]
opt[1][bar]
etc...
The index (1,2,etc...) does not correspond to row IDs in the database, it is simply a way to split up the groups of fields. There may be gaps in the index as users are able to add and remove an arbitrary number of the field groups. All groups are identical, that is, they contain exactly the same set of fields with the same second level names.
I want to be able to use CodeIgniter's validation library to validate the form and (p)re-populate as necessary. I've found plenty of posts (in addition to the excellent CI user guide) on the pre-populating and I know how to get the working with the re-populating in general. However, this is the first time I've had to try it with the indexed field names as above. I've tried the below and it doesn't work:
array(
'field' => 'opt[][foo]',
'label' => 'Foo',
'rules' => 'required'
)
I'm guessing I was just hoping for too much and CodeIgniter doesn't support what I need it to do. Extending the existing form validation library is an option so if anyone has been in the same situation and can provide some tips that would be very welcome.
UPDATE:
Just a little extra info, I've also tried validating a specifically indexed field (see below) and that also didn't work... As I understand it multidimensional validation should work in the specific case:
array(
'field' => 'opt[0][foo]',
'label' => 'Foo',
'rules' => 'required'
)
The following controller code works for me on CI 2.0.2
public function test() {
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('test[test1][test2]', 'Test', 'required|valid_email');
$this->form_validation->run();
echo validation_errors();
echo form_open($this->uri->uri_string());
echo form_input('test[test1][test2]', set_value('test[test1][test2]'));
echo form_submit();
echo form_close();
}
You can use this to loop through the opt variable and set validation rules for each input.
if(!empty($opt))
{
foreach($opt as $id => $value)
{
$this->form_validation->set_rules('opt[' . $id . '][foo]', 'Foo', 'required');
$this->form_validation->set_rules('opt[' . $id . '][bar]', 'Bar', 'required');
}
}
You should take a look at the callback functions for the validating class - this should help you accomplish what you need for validation.
I have a controller which I use for a login form. In the view, I have a {error} variable which I want to fill in by using the parser lib, when there is an error. I have a function index() in my controller, controlled by array $init which sets some base variables and the error message to '':
function index()
{
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$this->parser->parse('include/header', $init);
$this->parser->parse('login/index', $init);
$this->parser->parse('include/footer', $init);
}
At the end of my login script, I have the following:
if { // query successful }
else
{
$init['error'] = "fail";
$this->parser->parse('login/index', $init);
}
Now, of course this doesn't work. First of all, it only loads the index view, without header and footer, and it fails at setting the original $init['error'] to (in this case) "fail". I was trying to just call $this->index() with perhaps the array as argument, but I can't seem to figure out how I can pass a new $init['error'] which overrides the original one. Actually, while typing this, it seems to impossible to do what I want to do, as the original value will always override anything new.. since I declare it as nothing ('').
So, is there a way to get my error message in there, or not? And if so, how. If not, how would I go about getting my error message in the right spot? (my view: {error}. I've tried stuff with 'global' to bypass the variable scope but alas, this failed. Thanks a lot in advance.
$init musst be modified before generating your view.
To load your header and footer you can include the following command and the footer's equivalent into your view.
<?php $this->load->view('_header'); ?>
to display errors, you can as well use validation_errors()
if you are using the codeigniter form validation.
if you are using the datamapper orm for codeigniter you can write model validations, and if a query fails due to validation rule violation, you get a proper error message in the ->error property of your model.
Code for your model:
var $validation = array(
'user_name' => array(
'rules' => array('required', 'max_length' => 120),
'label' => 'Name'
)
);
You might try this:
function index() {
$init = array(
'base_url' => base_url(),
'title' => 'Login',
'error' => ''
);
$string = $this->parser->parse('include/header', $init, TRUE);
$string .= $this->parser->parse('login/index', $init, TRUE);
$string .= $this->parser->parse('include/footer', $init, TRUE);
$this->parser->parse_string(string);
}
In parse()you can pass TRUE (boolean) to the third parameter, when you want data returned instead of being sent (immediately) to the output class. By the other hand, the method parse_string works exactly like `parse(), only accepts a string as the first parameter in place of a view file, thus it works in conjunction.