Codeigniter add validation for multiple element - codeigniter

My form has more than 50 different text inputs. I would like to use CodeIgniter's validations (like trim function) in the form validation library without creating a rule for each input. Is it to possible to combine them into one rule so I don't have to waste my time writing the same code over and over?

Change text field name as group_name[your_txt_names] in your view
<input name="group_name[your_txt_names]" value="" type="text" />
Then in controller, you can create a function.
$txt_bxes = $this->input->post("group_name");
$post_vals = array_map('trim', $txt_bxes);
Now you have trimmed values in your array.

Kumar_v's idea was on the right track, if a bit silly in implementation
$this->input->post('var); merely reads the $_POST and runs some sanitation on it; the validation rules merely read the var from $_POST and apply your validation rule.
So if you only want to trim all $_POST vars, just trim your $_POST directly, then you can also run other validation afterwards.
Solution:
$_POST = array_map('trim', $_POST);
or
// take all posts and dump them into a variable at once
$input = $this->input->post(null, true);
$input = array_map('trim', $input);

as the post data comes in array, I hope this will help you
$postData = $this->input->post();
array_walk($postData ,'myFunc');
function myFunc(&$value,$key){
$value = trim($value);
}

Related

Get Input Data Value in Controller in Laravel

I want to get the value of this input.
<input type="text" name="txtEmployeeNo" value='{{ $employee->employee_no }}'>
Its value is 53210. How can I get that in my controller?
I currently have this on my controller.
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where(['employee_no'=>$employeeNum])->get();
return view('admin.employeemaintenance.createSchedule',compact(,'employeeSched'));
The problem is when I open and see if it is fetched nothing is showing. I cannot get the input.
Try this, It should must work.
$employeeNum = (isset($request['txtEmployeeNo'])) ? $request['txtEmployeeNo'] : 0;
$employeeSched = Schedule::where(['employee_no'=>$employeeNum])->get();
return view('admin.employeemaintenance.createSchedule',$employeeSched);
In your controller insert this line after opening your function:
dd($request->all);
It will show you everything that has been posted through your form with values. If you get your 'txtEmployeeNo' without value, it means something went wrong when you insterted it in your input.
Check with dev tools if that specific input has any value.
If your input has the value you mentioned and your $request->all() still shows an empty value for your "txtEmployeeNo", then the error is in the HTML/Blade file.
Make sure you create the form correctly
Make sure your input's name equals with the request you are trying to receive in your controller.
If you get null as the value of the $request, that could mean, in your Blade file, the input also has it's value as null.
Try to manually insert a value like <input type="text" name="txtEmployeeNo" value="2"> and see if you get that in your controller. If you do, then the query in your input is wrong.
That's all I could think of without provided Blade and Controller code.
Try this:
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where('employee_no', $employeeNum)->get();
return view('admin.employeemaintenance.createSchedule',compact('employeeSched'));
well, here is an edit to this answer with the steps needed:
in your routes:
Route::post('yourRouteName','yourController#nameOfFunctionInController')->name('TheNameOfTheRoute');
In your controller:
public function nameOfFunction(Request $request) {
$employeeNum = $request->input('txtEmployeeNo');
$employeeSched = Schedule::where('employee_no', $employeeNum)->get();
return view('admin.employeemaintenance.createSchedule',compact('employeeSched'));
}
And that's it basically.

Laravel, return view with Request::old

fHello, for example, i have simple input field (page index.php)
<input type="text" name="name" value="{{Request::old('name')}}">
In controller
$this->validate($request, ['name' => 'required']);
After this, i want make some check without Laravels rules. For example
if($request['name'] != 'Adam') { return view('index.php'); }
But after redirect, Request::old is empty. How to redirect to index.php and save old inputs and use Request::old, or its impossible? Thank you.
PS its example, i know that Laravel has special rules for check inputs value
Old question, but for future reference, you can return the input to a view by flashing the request input just beforehand.
i.e.
session()->flashInput($request->input());
return view('index.php');
then in your view you can use the helper
{{ old('name') }}
or
{{Request::old('name')}}
In Laravel 8.x, you can simply use $request->flash();
Docs: https://laravel.com/docs/8.x/requests#flashing-input-to-the-session
You can use back() instead if any url. These function helps you in any case to be able to return to previous page without writing route.
return back()->withInput();
To add the input to your request try adding:
return view('index.php')->withInput();

Codeigniter custom helper for bbcode, apply function on parameter

I made a custom bbcode parser function and added it on my helper
if ( !function_exists('bbcode_parser'))
{
function bbcode_parser($str)
{
$patterns = array(
'#\[b\](.*?)\[/b\]#is',
'#\[img\](.*?)\[/img\]#is',
'#\[url\](.*?)\[/url\]#is',
'#\[url=(.*?)\](.*?)\[/url\]#is'
);
$replacements = array(
'<strong>$1</strong>',
'<img src="$1" />',
'$1',
'$2',
);
$str = preg_replace($patterns, $replacements, $str);
return $str;
}
}
It's good and works like I want it to but my question is how to apply a function on each replacement value.
fe. for the url that doesn't have inner data, i want to replace with the website title of the url
or validate the url if it has http://
i would also like to check the size of the image, if it's too large, i want to resize it when printed by adding a "width" attribute and then just add an tag to the full size image.
is this possible? if so, how to do this?
You can implement this with preg_replace_callback()
http://www.php.net/manual/en/function.preg-replace-callback.php
Only the matched elements will be passed to the callback, so you would be able to create the callbacks you need or apply a standard replace for the normal regex patterns.

Codeigniter form validation allow numeric type to include comma

When validating prices with CI I use the following rule;
$this->form_validation->set_rules('price','lang:price','required|numeric|greater_than[0.99]');
Is there any way to allow commas in this rule line? Or do i have to create a callback?
Codeigniter 3 offers a regex validation. Form Validation
Using the regex given by Ben... No callback is required.
$this->form_validation->set_rules('price','lang:price','required|numeric|greater_than[0.99]|regex_match[/^[0-9,]+$/]');
From using the form validation library, I've never seen anything that would allow you to do that without a callback.
This would be the callback though:
function numeric_wcomma ($str)
{
return preg_match('/^[0-9,]+$/', $str);
}
with a rule of
$this->form_validation->set_rules('input', 'Input', 'callback_numeric_wcomma');
My answer is:
$this->form_validation->set_rules('price','lang:price','regex_match[/^(?!0*[.,]?0+$)\d*[.,]?\d+$/m]');
or do it in your codeigniter view. Add script:
<script>
function replace(element) {
// set temp value
var tmp = element.value;
// replace everything that's not a number or comma or decimal
tmp = tmp.replace(/[^0-9,.,-]/g, "");
// replace commas with decimal
tmp = tmp.replace(/,/, ".");
// set element value to new value
element.value = tmp;
}
</script>
and then use input like this:
<input id="something" onkeyup="replace(this)" type="text">

CodeIgniter Form Validation with existing $_POST data

I have a form that I need to validate but I can't figure out how to code the controller so that it works correctly the first time the page is displayed. Here is my code (simplified):
function index()
$data['somedata'] = $this->input->post('somedata');
$this->form_validation->set_rules('event', 'Event', 'trim|required|alpha_numeric');
... more set_rules ...
if($this->form_validation->run() == FALSE)
{
// Hasn't been run or there are validation errors
$this->load->view('eventview', $data);
}
else
{
// Process the event
}
}
The problem is that form_validation->run() is never FALSE because the $_POST array contains data from a previous form that is used by this second form. At the very beginning of the form_validation->run() function is the following code:
// Do we even have any data to process? Mm?
if (count($_POST) == 0)
{
return FALSE;
}
Since $_POST data exists the count is always greater than zero which results in the validation to be processed on initial page load.
Any suggestions as to how I might work around this?
I would suggest that you save the data from your first form in sessions, then make a redirect to your second form instead of going directly to the next one, with your post data.
This would also be more flexible if you need to reuse any of the submitted data.
In the first form set a hidden input
<input type="hidden" name="form1" value="form1" />
Then in your controller check if the field is set, if so store the current post array, and then unset it.
if(isset($_POST['form1'])){
$old_post = $_POST;
unset($_POST);
}
as I assume you are accessing the $_POST array in your view, instead pass `$old_post` through and use that,
e.g. (isset($old_post) ? $old_post['field_name'] : set_value('field_name))
Good luck.

Resources