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

(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();    
= [
                "dh_phone_number" => [
                  "label" => "Phone"
                  "rules" => "teleNumberValidation[dh_phone_number,dh_phone_country]",


in the teleNumberValidation i want to do something like this;

    try {
        } 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;

          return redirect()->back()
        ->with('errors', $validation->getErrors())
        ->with('warning', 'Invalid Data')
Any pointers appreciated.

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

(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.

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

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!

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.

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

Theme © iAndrew 2016 - Forum software by © MyBB