DEV Community

Helmi M.
Helmi M.

Posted on

1

How to validate POST and non-POST data in Codeigniter 4

This is just a snippet of code so that I can refer back in the future if required.

How do you validate non-POST dan POST data in Codeigniter 4 without resorting to creating your own validation rules?

Let say we have a very simple form with one input:

<input type="text" name="item">
Enter fullscreen mode Exit fullscreen mode

And we also have a data set acquired from somewhere else:

$data['price']= "5"
Enter fullscreen mode Exit fullscreen mode

The key is to have our validation runs with a variable:

$validation->run($post)
Enter fullscreen mode Exit fullscreen mode

First we set $post to combine both our POST and non-POST data:

$post = array_merge($request->getPost(), $data);
Enter fullscreen mode Exit fullscreen mode

Then we run our validation script as required:

\\ set our validation rules
$validation->setRules([
    'item' => 'required',
    'price' => 'greater_than[0]'
]);

if(! $this->validation->run($post)) {
// error
} else {
// success
}
Enter fullscreen mode Exit fullscreen mode

Hope this helps.

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay