-
Codinglander
Member
-
Posts: 62
Threads: 14
Joined: Jan 2018
Reputation:
1
04-22-2020, 10:48 PM
(This post was last modified: 04-22-2020, 10:50 PM by Codinglander.)
Hi there, I'm back
I have some Problems with the validation tutorial. I followed the steps for my own little project, but it doesn't work yet.
Here my code:
BaseController (part):
PHP Code: public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger) { // Do Not Edit This Line parent::initController($request, $response, $logger);
//-------------------------------------------------------------------- // Preload any models, libraries, etc, here. //-------------------------------------------------------------------- // E.g.: // $this->session = \Config\Services::session();
$this->session = \Config\Services::session(); $this->router = \Config\Services::router(); $this->validation = \Config\Services::validation();
// Sample-data for the views $this->data = [ 'title' => 'defaultTitle', 'main_headline' => 'Main Headline', 'sitename' => 'defaultSite', 'menu_top' => array(), 'cur_controller' => $this->router->controllerName(), 'cur_method' => $this->router->methodName(), ];
}
Controller with validation (part):
PHP Code: public function sitesettings() { $this->validation->setRules([ 'site_admin_name' => 'min_length[3]|max_lenght[250]', 'site_admin_email' => 'min_length[3]|max_length[250]|valid_email', 'site_admin_pass_curr' => 'required_without[site_admin_pass_new,site_admin_pass_new_retype]', 'site_admin_pass_new' => 'min_length[8]', 'site_admin_pass_new_retype' => 'matches[site_admin_pass_new]', 'site_name' => 'max_length[200]', 'site_description' => 'min_length[3]', 'site_keywords' => 'min_length[3]', 'u_c_reason' => 'min_length[3]', 'u_c_more_infos' => 'min_length[3]'
]); if(! $this->validate([])) { $this->_set_active(4,1); // for my data['menu_top'] $this->data['main_headline'] = 'Site Settings <small style="color: #6C757D; font-size: 40%">Use the input fields to change value. Keep them clear to change nothing.</small>'; $this->data['validation'] = $this->validator; echo view('admin/sitesettings',$this->data); } else{ $this->_set_alert('Speichern erfolgreich.','Die Site-Daten wurden erfolgreich übernommen'); pre_output($_POST,true); } }
The Form (part) :
Code: <div class="col-sm-12">
<?= $validation->listErrors() ?>
</div>
<form action="<?php echo base_url('admin/sitesettings') ?>" accept-charset="UTF-8" method="post">
<?= csrf_field() ?>
<div class="row" style="margin-bottom: 16px;">
<div class="col-sm-12">
<div class="card-deck">
<div class="card">
<img src="https://dummyimage.com/490x123/a81ca8/2da337.png&text=+" class="card-img-top" alt="...">
<div class="card-img-overlay">
<h4><i class="fa fa-info-circle fa-fw"></i> Admin Infos</h4>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-12">
<div class="form-group input input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-user fa-fw"></i></span>
</div>
<span class="has-float-label">
<input class="form-control" id="site_admin_name" name="site_admin_name" type="text" placeholder="Admin Name">
<label for="site_admin_name">Admin Name</label>
</span>
</div>
<div class="site_settings_helptext">
<mark>Current:</mark> My Name
</div>
</div>
I set up the rules WITHOUT any "required" rule, so it should pass if only one field is filled up.
In the debugbar the $_POST array ist correctly filled out, but the form everytime is still reloaded instead of showing my success-screen.
Where is my issue ?!?
-
Leo
Member
-
Posts: 108
Threads: 11
Joined: Jun 2017
Reputation:
1
"I set up the rules WITHOUT any "required" rule, so it should pass if only one field is filled up.
In the debugbar the $_POST array ist correctly filled out, but the form everytime is still reloaded instead of showing my success-screen.
Where is my issue ?!?"
Try adding permit_empty to all rules. For ex: 'site_admin_name' => 'permit_empty|min_length[3]|max_lenght[250]',
You can see things I made with codeigniter here: itart.pro its not overly impressive as I have very little time to learn.
-
jreklund
Administrator
-
Posts: 1,408
Threads: 3
Joined: Aug 2017
Reputation:
43
You are overriding your own validation that you have set in BaseController.
This are a stand alone function, that you pass your rules directly into that array.
$this->validate([])
If wan't to use setRules() you need to runt it like this:
if($this->validation->withRequest($this->request)->run()).
Here you can see the actual code that stand alone function executes.
PHP Code: /** * A shortcut to performing validation on input data. If validation * is not successful, a $errors property will be set on this class. * * @param array|string $rules * @param array $messages An array of custom error messages * * @return boolean */ protected function validate($rules, array $messages = []): bool { $this->validator = Services::validation();
// If you replace the $rules array with the name of the group if (is_string($rules)) { $validation = config('Validation');
// If the rule wasn't found in the \Config\Validation, we // should throw an exception so the developer can find it. if (! isset($validation->$rules)) { throw ValidationException::forRuleNotFound($rules); }
// If no error message is defined, use the error message in the Config\Validation file if (! $messages) { $errorName = $rules . '_errors'; $messages = $validation->$errorName ?? []; }
$rules = $validation->$rules; }
return $this->validator ->withRequest($this->request) ->setRules($rules, $messages) ->run(); }
-
Codinglander
Member
-
Posts: 62
Threads: 14
Joined: Jan 2018
Reputation:
1
04-23-2020, 07:49 PM
(This post was last modified: 04-23-2020, 08:18 PM by Codinglander.)
We are slowly getting closer
I found two typing errors and now it almost works with validation.
When I call up the form for the first time, I shouldn't get any error messages via
Code: <?= $validation->listErrors() ?>
But the list of errors is displayed.
If I continue to fill out a few fields, the form should still be "submitted", but I don't get to the success page (where I just want to get the $ _POST array printed).
Where is my mistake?
Here is my updated code:
Controller:
PHP Code: public function sitesettings() { $this->validation->setRules([ 'site_admin_name' => 'min_length[3]|max_length[250]', 'site_admin_email' => 'min_length[3]|max_length[250]|valid_email', 'site_admin_pass_curr' => 'required_with[site_admin_pass_new,site_admin_pass_new_retype]', 'site_admin_pass_new' => 'min_length[8]', 'site_admin_pass_new_retype' => 'matches[site_admin_pass_new]', 'site_name' => 'max_length[200]', 'site_description' => 'min_length[3]', 'site_keywords' => 'min_length[3]', 'u_c_reason' => 'min_length[3]', 'u_c_more_infos' => 'min_length[3]'
]); if(! $this->validation->withRequest($this->request)->run()) { $this->_set_active(4,1); $this->data['main_headline'] = 'Site Settings <small style="color: #6C757D; font-size: 40%">Use the input fields to change value. Keep them clear to change nothing.</small>'; $this->data['validation'] = $this->validation; echo view('admin/sitesettings',$this->data); } else{ pre_output($_POST,true); } }
-
Codinglander
Member
-
Posts: 62
Threads: 14
Joined: Jan 2018
Reputation:
1
(04-24-2020, 09:40 AM)jreklund Wrote: It always execute it no matter what. It dosen't check if you posted any data. Haven't looked in the code in depth if you can actually fix it.
I added this to "fix" the problem. If it's a get request, don't try to look for $_POST and validate it.
PHP Code: if( $this->request->getMethod() === 'get' || ! $this->validate([]) ) {
} else { }
Thank you very much, this workaround does its job first. But there still has to be a reason why the tutorial methods didn't work.
I am interested in a clean, long-term solution
Greetings !
-
jreklund
Administrator
-
Posts: 1,408
Threads: 3
Joined: Aug 2017
Reputation:
43
That's because you are using it wrong. If you are referring to $this->validate().
The tutorial command are a complete solution, you have created a three step process. Please refer to the post I made earlier, I copied the complete source code for it. You have created all those steps it does separately.
You are supposed to use it like this:
PHP Code: $rules = [ 'site_admin_name' => 'min_length[3]|max_lenght[250]', 'site_admin_email' => 'min_length[3]|max_length[250]|valid_email', 'site_admin_pass_curr' => 'required_without[site_admin_pass_new,site_admin_pass_new_retype]', 'site_admin_pass_new' => 'min_length[8]', 'site_admin_pass_new_retype' => 'matches[site_admin_pass_new]', 'site_name' => 'max_length[200]', 'site_description' => 'min_length[3]', 'site_keywords' => 'min_length[3]', 'u_c_reason' => 'min_length[3]', 'u_c_more_infos' => 'min_length[3]', ];
if( $this->request->getMethod() === 'get' || ! $this->validate($rules) ) { // ... } else { // ... }
-
hugoafr
Newbie
-
Posts: 8
Threads: 3
Joined: Jun 2020
Reputation:
0
Tengo el mismo probema, no me funciona la validación.
He logrado mostrar los mensajes de error, pero no considera los datos por POST.
I have the same problem, validation does not work for me.
I have managed to display the error messages, but do not consider the data by POST.
PHP Code: $this->validation->setRule('data_form[usuario]', 'Usuario', 'trim|required'); $this->validation->setRule('data_form[password]', 'Contraseña', 'trim|required'); $this->validation->setRule('data_form[id_sucursal]', 'Sucursal', 'trim|required');
if (!$this->validate($this->validation->getRules())){
|