Welcome Guest, Not a member yet? Register   Sign In
Throw Exception, Validation and Error Handling
#1

(This post was last modified: 04-04-2022, 09:13 PM by spreaderman.)

Struggling here.  I have a form with validation.  I have a custom rule with a callback method.  In the callback method, I have a try/catch exception on a google lib that has a good number of custom validation messages eg, not a valid phone number, phone number too long, etc).  How can I validate the form and also get back the custom message

PHP Code:
          // validates the phone number.  takes a phone number and a country code.
            $validation =  \Config\Services::validation();    
            $rules 
= [
                "dh_phone_number" => [
                  "label" => "Phone"
                  "rules" => "teleNumberValidation[dh_phone_number,dh_phone_country]",

                ], 

in the teleNumberValidation i want to do something like this;

   
Code:
    try {
            checkNumber(dh_phone_number,dh_phone_country);
        } catch(\Exception $e) {
            return $e->getMessage();
        } finally {
            return true;
        }

but validation only accepts true or false so how can I get $e->getMessage() into something like this;

     
Code:
          return redirect()->back()
        ->with('errors', $validation->getErrors())
        ->with('warning', 'Invalid Data')
        ->withInput();
Any pointers appreciated.
Reply
#2

See https://codeigniter4.github.io/userguide...stom-rules
Use &$error.
Reply
#3

(04-04-2022, 10:16 PM)kenjis Wrote: See https://codeigniter4.github.io/userguide...stom-rules
Use &$error.

Hi Kenjis, thank you for the link. I have read through it but not sure still how I would return the exception error message. If you could kindly let me know a bit more. I have tried to dig through other projects like bonfire 2 to try to find how it is done but I am also finding it hard to get an example.
Reply
#4

Something like this:

PHP Code:
    public function teleNumberValidation(
        $strstring $fields, array $datastring &$error null
    
): bool {
        // ...

        $error $e->getMessage();

        // ...
    

See also https://codeigniter4.github.io/userguide...parameters
Reply
#5

Thank you Kenjis.

Almost clear. I don’t understand the need to pass in &$error in my case. Also, no need to return $error. I am also not clear on references but am reading about them still. Thanks!
Reply
#6

See https://www.php.net/manual/en/language.r...s.pass.php

The validation method must return boolean. So it can't return error strings.
So we use Passing by Reference.
Reply
#7

Fantastic. Read all about references. Understood now. Many Thanks Kenjis.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB