I am currently having an issue with validation on dynamic forms in code igniter.
<input name="item1_name[0][PostTitle]">
<input name="item1_name[0][PostSubject]">
<input name="item1_name[0][PostMessage]">
<input name="item1_name[0][PostSlug]">
<input name="item1_name[1][PostTitle]">
<input name="item1_name[1][PostSubject]">
<input name="item1_name[1][PostMessage]">
<input name="item1_name[1][PostSlug]">
Above is a part of my form. This form submits the data as an array. What I want to do is be able to use the codeigniter form validator to validate all the fields. The problem with this currently is that the form is dynamic. The front end allows these sets of inputs to be multiplied an infinite amount of times using javascript. Does anyone have any ideas on how I could solve this issue?
You can use the below method...
//get the array
$item1_name = $this->input->post('item1_name', TRUE);
foreach ($item1_name as $key => $item1_name)
{
// Set the rules
$this->form_validation->set_rules($key."[PostTitle]", "PostTitle", "trim|required");
$this->form_validation->set_rules($key."[PostSubject]", "PostSubject", "trim|required");
$this->form_validation->set_rules($key."[PostSubject]", "PostSubject", "trim|required");
$this->form_validation->set_rules($key."[PostSlug]", "PostSlug", "trim|required");
}
Write your own validation function and handle the array however you'd like:
$this->form_validation->set_rules('item1_name', 'Item Name', 'callback_item_name_check');
function item_name_check($value)
{
// evaluate $value and return TRUE or FALSE with error message
if ($value == 'test')
{
$this->form_validation->set_message('item_name_check', 'You need to enter something else.');
return FALSE;
}
else
{
return TRUE;
}
}
More in CodeIgniter documentation.
Related
In my controller, I validate the input fields and if any validation fails I want to return back to the form and refill the previous values that the user was inputing (if there is any other easier way instead this please tell me). But here is what I'm doing:
Controller.php:
public function store(Request $request, AnexoController $anexoController)
{
$validator = Validator::make(
$request->all(),
$rules,
$messages
);
if($validator->fails())
{
return Redirect::to($request->headers->get('referer'))
->withErrors($validator)
->withReq($request->all());
}
// continues the function...
}
At the view.blade.php:
<input type="text"
maxlength="256"
id="text-input"
name="id"
placeholder="Código"
class="form-control"
#if(isset($req)) value="{{$req->id}}"
#else value="$REQ VARIABLE NOT SET"
#endif
required>
And when I test it, the field id value is set to "$REQ VARIABLE NOT SET" but $errors from $validator variable is set. So, why isn't the variable $req being set in this context? Thanks in advance.
Use this
$request->validate([
//rules
]);
It will automatically return to form page with all the errors and inputs,
In your form you'll neet do add a helper in value of inputs for old inputs
<input type="text" value={{ old('email')}} name="email">
see https://laravel.com/docs/5.8/validation & https://laravel.com/docs/5.8/helpers
I am trying to apply some validation rules to my form data in CodeIgniter.
Expected Allowed output example like this: 22-some society, some street, city. 223399
What I Entered for check the validation: 42-some Society-3, some street. arcade ###*
This is my function which I use to validate the address.
function addr_line1($addr_line1) {
if (preg_match('/^[a-z0-9 .\-]+$/i',$addr_line1) !== FALSE)
return TRUE;
$this->form_validation->set_message('addr_line1', 'allow only space,comma,dot,numbers and alphabets.');
return FALSE;
}
Now I put all my validation in the config/form_validation.php
array(
'field' => 'addr_line1',
'label' => 'Address Line One',
'rules' => 'required|max_length[100]|callback_addr_line1'
),
After all this,I didn't get any validation error.
Am I not following the proper process?
or what should the regex code to validate this type of data?
change from
function addr_line1($addr_line1) {
if (preg_match('/^[a-z0-9 .\-]+$/i',$addr_line1) !== FALSE)
return TRUE;
$this->form_validation->set_message('addr_line1', 'allow only space,comma,dot,numbers and alphabets.');
return FALSE;
}
to
function addr_line1($addr_line1) {
if (preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $addr_line1))
{
$this->form_validation->set_message('addr_line1', 'allow only space,comma,dot,numbers and alphabets.');
}else{
return true;
}
}
Note:- you can replace £$%&*()}{##~?><>,|=_+¬- with your disallowed character
After Your suggestion and help, I finally found the correct Function.
function _validAddressCheck($addr_line1) {
if (preg_match('/^[0-9a-zA-Z .,-]+$/',$addr_line1)){
return TRUE;
} else {
$this->form_validation->set_message('_validAddressCheck', 'Only Allowed space, comma, dot, dash, numbers and alphabets.');
return FALSE;
}
}
I found that some rules which we have to follow if we are applying callback to the validation.
I have created config validation array at the application/config/form_validation.php
Put the callback function at the controller where I called that validations.
Find this link for creating a regex and test that. Link
<tr>
<td>
<label for="address">Address:</label></td><td>
<textarea name="address" placeholder="Write
something.."><?php echo set_value('address'); ?> </textarea>
</td>
<td>
<p class="err_msg">
<?php
echo form_error('address');
?>
</p>
</td>
in route page:-
$this->form_validation->set_rules('address','add','required|exact_length[18]',array('required'=>"Please Enter Address",'exact_length'=>"Please Enter At Least 10 Character"));
I'm learning Codeigniter and I have a controller named Admin controller
class Admin extends CI_Controller{
/* skipped */
//This function is used to generate changepassword form
public function changepassword(){
$this->data['sessiondata'] = $_SESSION['logged_in'];
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
}
//changepassword form will be submitted to this function ('admin/checkpassword')
public function checkpassword(){
$error = array(
'required' => '%s tidak boleh kosong',
'matches' => '%s tidak sama, dumb ass'
);
/* some validations skipped */
if($this->form_validation->run($this) == FALSE){
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"oldpassword" => $this->input->post('oldpassword'),
"newpassword" => $this->input->post('newpassword'),
"verifynewpasswprd" => $this->input->post('verifynewpassword')
);
$this->admincrud->changepassword($tobesent);
$this->data['result'] = "Password sukses diubah";
$this->data['mainview'] = 'components/admin/changepassword';
$this->load->view($this->layout, $this->data);
}
}
}
the result is, each time I go to base_url('admin/changepassword'), fill the provided form and then submit the form, my url changes from base_url('admin/changepassword') into base_url('admin/checkpassword'), which I know came as the result of submitting the form. Also each time I type base_url('admin/checkpassword') directly on my address bar, it opens the form, which I know came as the result of the if-else condition in checkpassword function. My question is, from the security standpoint, is it okay if I keep using this structure? and how can I prevent users from directly accessing base-url('admin/checkpassword') and instead redirecting them to base_url('admin/changepassword') ?
well if you don't want the URL to be changed after submitting the form.
You can use redirect('admin/changepassword'); and since you need to provide
messages accordingly, you can use $this->session->set_flashdata('msg','Your message'); before redirection and use it in view like this:
<?php if($this->session->flashdata('msg') <> NULL){echo $this->session->flashdata('msg');} ?>
Solution to your problem is $_SERVER['REQUEST_METHOD'] if i understood correctly...
For example :-
if($_SERVER['REQUEST_METHOD'] == 'POST')//form method is post
{
//checkpassword code
}
else
{
redirect(base_url('admin/changepassword'));
}
I am creating a search page in my CodeIgniter project.
On submit, the form calls the controller function, data is fetched via model function and the resulting array is passed to the view
The problem is that when I refresh the result page the form is resubmitting because the $_POST data is still there in the request headers.
How can I avoid that resubmit confirmation message
Following is the code for my form :
<!--form-->
<form id="find" action="<?php echo base_url()?>search/find" method="post">
<input type="text" name="search_key" class="tb4" id="search_key" placeholder="Search here"/>
<input type="button" value="search"/>
</form>
Following is the code for my controller:
/*
* function for fetching search results
* #param void
* #return void
*/
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Kindly help me with this.I can't use redirect instead of loading the view since I am bound to pass the result array $data to the view.
Try redirect to itself
public function find()
{
$data['search_result']=$this->search_model->search($this->input->post('search_key'));
if($this->input->post('search_key')) {
redirect('yourcontroller/find');
}
$this->load->view('template/header');
$this->load->view('pages/search_result',$data);
$this->load->view('template/footer');
}
Simple solution is to have a hidden timestamp field in the form.
<?php echo form_hidden( 'TS', time() ); ?>
When the form is processed, save this timestamp in the session,
$this->session->set_userdata( 'form_TS', $this->input->post( 'TS' ) );
Before processing the form check that two timestamps doesn't match
if ( $this->input->post( 'TS' ) != $this->session->userdata('form_TS') )
{...}
IF you want to avoid the resubmit then please after save redirect on same controller like this
It can be solved using session. If there is any POST form submit,
ie
if (count($_POST) > 0){
$this->session->set_userdata('post_data', $_POST );
redirect('same_controller');
}
else{
if($this->session->userdata('post_data')){
$_POST = $this->session->userdata('post_data');
$this->session->unset_userdata('post_data');
}
}
Kindly use this:
$post_data = $this->session->userdata('post_data');
if ($post_data == $_POST){
$this->session->unset_userdata('post_data');
redirect(current_url(), 'refresh');
}else{
$this->session->set_userdata('post_data', $_POST );
}
I have a controller which loads the view like this:
class A extends Controller{
public function simpleForm(){
//this generates the form
}
public function simpleFormSubmitted(){
// Simple form is submitted here. Here I perform validation and if
// validation fails I want to display simpleform again with all the values
// inputted by the user as it is and if validation succeeds I want to
// redirect to some other page. I am using simple HTML to generate the
// form and not the formhelper of CodeIgniter because I am more comfortable
// with HTML rather than remembering the syntax of CodeIgniter.
}
}
Here is how to preserve the form fields when dealing with errors...
$fields['username'] = 'Username';
$fields['password'] = 'Password';
$fields['passconf'] = 'Password Confirmation';
$fields['email'] = 'Email Address';
$this->validation->set_fields($fields);
This is how to re-populate the HTML form...
<?php echo $this->validation->error_string; ?>
<?php echo form_open('form'); ?>
<h5>Username</h5>
<input type="text" name="username" value="<?php echo $this->validation->username;?>" size="50" />
For more information look over here - Form Validation in Codeigniter
Look for the heading Re-populating the form
in function simpleForm add default variables so, after validation you can call it again with userform values
class A{
public function simpleForm($val1="", val2="", $val3=""){
//this generates the form
}
public function simpleFormSubmitted(){
//simple form is submitted here. Here is perform validation and if validation fails i
if(!$valid){
$result = $this->simpleForm($val1, $val2, $val3 etc...)
}
else{
$result = //whatever you need to output after validation success
}
return $result
}
}