Welcome Guest, Not a member yet? Register   Sign In
Noob Validation Custom Rule Function Quandry
#1

Hello there,
 
I’m a mid-life crisis career-change-wanna-be complete noob programmer (if noob’s the right term here?)- of about a week now- and particularly new to PHP, CI, webservers and suchlike… so apologies upfront for possible and probable stupid questions.
 
I have looked over examples (in CodeIgniter4 4.0.0-rc.2 documentation, and on the CI website– for both CI3 and CI4) and many of the problems/solutions/examples posted on websites like the CI Forum, CI Github, New Myth Media Blog, Stack Overflow etc, though many of them seem to be for CI3, which seems to have some notable differences (?).
 
In my learning process, I have started by trying to simulate user sign in functionality.  I have a Controller, two Views (not shown here, but really simply pages- one a pretty much just single form, and the other one a “blank” success HTML page), a set of custom rules in the Validation.php file, and a CustomRule.php file with the first of the methods that will implement all my custom rules (which, ultimately, I’d like to have all set in the Validation.php file).  For lack of a better idea, I’ve stuck the CustomRules.php file in the app\Config\ folder.
 
There are two parts to my problem:
 
1)  For the life of me, I can’t figure out how to get the Validation service to pass additional parameters (from the form) to my custom rules function called ‘user_validated’.  The CI4 documentation describes what the custom function needs to cater for when accepting additional parameters, but not how to trigger the Validation service to pass these additional parameters to one’s custom function… so although ‘user_validated’ is called, only ‘user_email_offered’ is ever passed as in as a string- nothing else goes in, from what I can tell.  How do I get around this?
 
2) If I manually set the parameter I need (that’s not being passed in the question above), the method runs, but gets stuck with an error saying: “Class 'UserModel' not found - APPPATH/Config\CustomRules.php at line 61”.  I’ve  tried calling with the full path (in line 61, and also using the USE statement above the CustomRules class, both with and without the path to UserModel.php (which is \app\Models\UserModel).  Do I have to put my UserModel.php in the same directory as my CustomRules.php file, or vice-versa?  Ideally, I’d like the models files to remain in the Models\ directory and the CustomRules.php (which, to me is a sub-function of the Validation.php configuration) to remain in the Config\ directory.  Is there a way to achieve this?
 
Extracts from my hack are appended below.
 
I’d be very grateful one of you knowledgeable folk could please point me in the right direction.
 
Thanks.
 
Regards,
Gary
 
 
In app\Controllers\SignupTest.php:
<?php
 
    namespace App\Controllers;
 
    use CodeIgniter\Controller;
 
    class SignupTest extends BaseController
    {
 
            public function index() {   // redirection from the default to signup(), signin(), ...
 
                return $this->signup();
 
            }
 
 
            public function signup() {
                        
                helper(['form']);
 
                $validation = \Config\Services::validation();
                
                if ($this->request->getPost()) {     // still TBD: any different to using $this->request->getGetPost() ?
 
                    $validationResult = $this->validate('user_signin'); // set the rules to use: 'user_signin', 'user_signup'
                    
                    if (!$validationResult) {
 
                        $validationErrors = $validation->getErrors();
 
                        return view('SignupTestView', $validationErrors);   // redisplay simple html form view with list of validation errors
                     
                    } else {
 
                        return view('SignupTestViewSuccess');  // display view to show success
                    }
                } else {
 
                    return view('SignupTestView');   // initial display, in the event of there being no POST data
 
                }
            }
    }
 
   
In \app\Config\CustomRules.php:
<?php

    namespace Config;
   
    use UserModel; // tried adding this to make UserModel visible to the call in uservalidated() method below, also referencing it with use app\Models\UserModel()
 
    //--------------------------------------------------------------------
    // Custom Rule Functions
    //--------------------------------------------------------------------
 
    class CustomRules
    {
       
   
        public function user_validated(string $str, string $fields = NULL, array $data = NULL, string &$error = NULL) : bool{           
 
             $user_email_offered = $str;
             $user_password_offered = '';    // to be extracted using $fields = explode(',', $fields), but $fields is never provided in the call to this user_validated method
            
 
            if (($user_email_offered !== NULL) && ($user_password_offered !== NULL)) {
               
                $usermodel = new UserModel();   // intended to create a UserEntity to permit connectivity to the database, but error thrown is:  Class 'UserModel' not found  or Class 'Config\app\Models\UserModel' not found, if I call it with “new app\Models\UserModel()” 
               
                $user_found = $usermodel->find($user_email_offered);    // we're going to assume that user_email is unique (which is a rule configured in the database table)
             
                if ($user_found === NULL) { // check if user exists before doing the more involved checks in the else-if section below, which may throw exceptions if there's nothing to compare (?)
               
                ...   
    
          }



    }
 
In \app\Config\Validation.php:
?php
    namespace Config;
 
    class Validation
    {
        //--------------------------------------------------------------------
        // Setup
        //--------------------------------------------------------------------
 
        /**
         * Stores the classes that contain the
         * rules that are available.
         *
         * @var array
         */
        public $ruleSets = [
            \CodeIgniter\Validation\Rules::class,
            \CodeIgniter\Validation\FormatRules::class,
            \CodeIgniter\Validation\FileRules::class,
            \CodeIgniter\Validation\CreditCardRules::class,
            \Config\CustomRules::class,
        ];
 
        /**
         * Specifies the views that are used to display the
         * errors.
         *
         * @var array
         */
        public $templates = [
            'list'   => 'CodeIgniter\Validation\Views\list',
            'single' => 'CodeIgniter\Validation\Views\single',
        ];
 
        //--------------------------------------------------------------------
        // Custom Rules
        //--------------------------------------------------------------------
 
        /* configurable limits for validation rules array below*/
        const user_email_min_lenth = 9
        const user_email_max_lenth = 50;
        const user_password_min_lenth = 6;  
        const user_password_max_lenth = 25
 
        
        public $user_signin = [
            'user_email' => [
                'label' => 'e-mail address',
                'rules' => 'trim|required|valid_email|user_validated'// user_validated is custom rule, that will have a custom error message
                'errors' => [
                    'required' => 'You must provide an {field}',
                    'valid_email' => 'Please enter a valid {field}',
                ]
            ],
            'user_password' => [
                'label' => 'password',
                'rules' => 'trim|required',
                'errors' => [
                    'required' => 'Enter a {field} to sign in',
                    'user_password_check' => 'No such user/{field} combination found',
                ]
            ]
        ];
 
 
 
Reply
#2

Totally unreadable. Font size 1 pt?
Reply
#3

I'll second that.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

(10-11-2019, 10:59 AM)InsiteFX Wrote: I'll second that.
Hi, sorry guys... it looked all fine when I typed it in, but when I checked with a preview, it came out minute... so I tried to change the font size... and it looked great again when I was editing it... but somehow still came out the same size.  I'll try another time.
Reply
#5

(10-11-2019, 10:59 AM)InsiteFX Wrote: I'll second that.
I'll try repost, but have fixed the second point of the problem myself, so I'll revise and repost (seemed to be case-sensitivity in the path (which I actually think is namespace where I was fiddling)... I thougth I'd tried all the options.  Maybe it was the wine.
Reply
#6

[repost attempt]

Hello there,

I’m a mid-life crisis career-change-wanna-be complete noob programmer (if noob’s the right term here?)- of about a week now- and particularly new to PHP, CI, webservers and suchlike… so apologies upfront for possible and probable stupid questions.
 
I have looked over examples (in CodeIgniter4 4.0.0-rc.2 documentation, and on the CI website– for both CI3 and CI4) and many of the problems/solutions/examples posted on websites like the CI Forum, CI Github, New Myth Media Blog, Stack Overflow etc, though many of them seem to be for CI3, which seems to have some notable differences (?).
 
In my learning process, I have started by trying to simulate user sign in functionality.  I have a Controller, two Views (not shown here, but really simply pages- one a pretty much just single form, and the other one a “blank” success HTML page), a set of custom rules in the Validation.php file, and a CustomRule.php file with the first of the methods that will implement all my custom rules (which, ultimately, I’d like to have all set in the Validation.php file).  For lack of a better idea, I’ve stuck the CustomRules.php file in the app\Config\ folder.
 
There are is two now one parts to my problem:
 
1)  For the life of me, I can’t figure out how to get the Validation service to pass additional parameters (from the form) to my custom rules function called ‘user_validated’.  The CI4 documentation describes what the custom function needs to cater for when accepting additional parameters, but not how to trigger the Validation service to pass these additional parameters to one’s custom function… so although ‘user_validated’ is called, only ‘user_email_offered’ is ever passed as in as a string- nothing else goes in, from what I can tell.  How do I get around this?
 
2) If I manually set the p...  Fixed - finger trouble
 
Extracts from my hack are appended below.
 
I’d be very grateful one of you knowledgeable folk could please point me in the right direction.
 
Thanks.
 
Regards,
Gary
 
 
In app\Controllers\SignupTest.php:
<?php
 
    namespace App\Controllers;
 
    use CodeIgniter\Controller;
 
    class SignupTest extends BaseController
    {
 
            public function index() {   // redirection from the default to signup(), signin(), ...
 
                return $this->signup();
 
            }
 
 
            public function signup() {
                        
                helper(['form']);
 
                $validation = \Config\Services::validation();
                
                if ($this->request->getPost()) {     // still TBD: any different to using $this->request->getGetPost() ?
 
                    $validationResult = $this->validate('user_signin'); // set the rules to use: 'user_signin', 'user_signup'
                    
                    if (!$validationResult) {
 
                        $validationErrors = $validation->getErrors();
 
                        return view('SignupTestView', $validationErrors);   // redisplay simple html form view with list of validation errors
                     
                    } else {
 
                        return view('SignupTestViewSuccess');  // display view to show success
                    }
                } else {
 
                    return view('SignupTestView');   // initial display, in the event of there being no POST data
 
                }
            }
    }
 
   
In \app\Config\CustomRules.php:
<?php

    namespace Config;
   
    use App\Models\UserModel;
 
    //--------------------------------------------------------------------
    // Custom Rule Functions
    //--------------------------------------------------------------------
 
    class CustomRules
    {
       
   
        public function user_validated(string $str, string $fields = NULL, array $data = NULL, string &$error = NULL) : bool{           
 
             $user_email_offered = $str;
             $user_password_offered = '';    // to be extracted using $fields = explode(',', $fields), but $fields is never provided in the call to this user_validated method
            
 
            if (($user_email_offered !== NULL) && ($user_password_offered !== NULL)) {
               
                $usermodel = new UserModel();   // intended to create a UserEntity to permit connectivity to the database
               
                $user_found = $usermodel->find($user_email_offered);    // we're going to assume that user_email is unique (which is a rule configured in the database table)
             
                if ($user_found === NULL) { // check if user exists before doing the more involved checks in the else-if section below, which may throw exceptions if there's nothing to compare (?)
               
                ...   
    
          }



    }
 
In \app\Config\Validation.php:
?php
    namespace Config;
 
    class Validation
    {
        //--------------------------------------------------------------------
        // Setup
        //--------------------------------------------------------------------
 
        /**
         * Stores the classes that contain the
         * rules that are available.
         *
         * @var array
         */
        public $ruleSets = [
            \CodeIgniter\Validation\Rules::class,
            \CodeIgniter\Validation\FormatRules::class,
            \CodeIgniter\Validation\FileRules::class,
            \CodeIgniter\Validation\CreditCardRules::class,
            \Config\CustomRules::class,
        ];
 
        /**
         * Specifies the views that are used to display the
         * errors.
         *
         * @var array
         */
        public $templates = [
            'list'   => 'CodeIgniter\Validation\Views\list',
            'single' => 'CodeIgniter\Validation\Views\single',
        ];
 
        //--------------------------------------------------------------------
        // Custom Rules
        //--------------------------------------------------------------------
 
        /* configurable limits for validation rules array below*/
        const user_email_min_lenth = 9
        const user_email_max_lenth = 50;
        const user_password_min_lenth = 6;  
        const user_password_max_lenth = 25
 
        
        public $user_signin = [
            'user_email' => [
                'label' => 'e-mail address',
                'rules' => 'trim|required|valid_email|user_validated'// user_validated is custom rule, that will have a custom error message
                'errors' => [
                    'required' => 'You must provide an {field}',
                    'valid_email' => 'Please enter a valid {field}',
                ]
            ],
            'user_password' => [
                'label' => 'password',
                'rules' => 'trim|required',
                'errors' => [
                    'required' => 'Enter a {field} to sign in',
                    'user_password_check' => 'No such user/{field} combination found',
                ]
Reply
#7

When you configure your rules in the Config/Validation file, you can try

$validation = \Config\Services::validation();
$validation->setRuleGroup('user_signin');
Reply
#8

Thanks for the suggestion, I originally had it like this, but found that I could move the setting of the rule group into the call to validate, using: $validationResult = $this->validate('user_signin');

I have taken it back to the way you suggest, just to be sure that I hadn't hashed something up the first time, but it still doesn't seem to be what triggers the additional data to be passed to the custom rule's method.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB