How to get a single validation rule from model in CodeIgniter 4?
Created:12 Oct 2021 00:05:56 , in Web development
Here is a little bit on how to get a single validation rule from a model in CodeIgniter 4. Why would you want to do a thing like this? Well, sometimes you want to validate only a single piece of input data, like for example a customer order code.
In Codeigniter 4 validation rules are stored in models.
To get a single rule from a model you would do something like this:
$rule = $orderModel -> getValidationRules(['only' => ['code']])['code'];
Here is how to use this in a broader context:
Supposed, that in your Order model among others you have a validation rule like this:
protected $validationRules = [
.
.
'code' => 'required|min_length[17]|max_length[40]|alpha_numeric',
.
.
];
and you want to use it in your controller without duplication.
To validate a code coming into your controller as user input with the rule above you would do something like this:
$code = trim(filter_var($code,FILTER_SANITIZE_STRING));
to sanitize the input string, and then
// if input data is valid:
if($validation -> check($code, $orderModel -> getValidationRules(['only' => ['code']])['code'])){
// input valid
// if it is not do this:
} else {
// input invalid
}
to validate it.
getValidationRules is yet another little things that makes CodeIgniter 4 such a cool little PHP framework.
This post was updated on 13 Oct 2021 12:01:05
Tags: CodeIgniter , php
Author, Copyright and citation
Author
Author of the this article - Sylwester Wojnowski - is a sWWW web developer. He has been writing computer code for the websites and web applications since 1998.
Copyrights
©Copyright, 2024 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.
Computer code, if present in the article, is excluded from the above and licensed under GPLv3.
Citation
Cite this article as:
Wojnowski, Sylwester. "How to get a single validation rule from model in CodeIgniter 4?." From sWWW - Code For The Web . https://swww.com.pl//main/index/how-to-get-a-single-validation-rule-from-model-in-codeigniter-4
Add Comment