Welcome Guest, Not a member yet? Register   Sign In
Validation Class passing field name
#1

(This post was last modified: 11-18-2021, 12:11 PM by sevmusic.)

How can I pass the field label to the validation class so I can return the error with the field label?

Previously, we could do a callback function with {field} and it would convert that into the field label to be returned with the error.

(ignore the goofy attempt at the validation rule checking for string length, I know that is already built in. This is strictly as an example)

MyController.php
PHP Code:
$this->validation->setRules([
    'first_name' => ['label' => 'First Name''rules' => 'myFieldCheck'],
]); 


MyValidationRules.php
PHP Code:
class MyValidationRules
{
    public function myFieldCheck(string $strstring &$error null): bool
    
{
        if(!strlen(trim($str)) > 0){
            $error 'The {field} field needs to be last least 1 character long.';
           return false;
       } else {
            return true;
        }
    }


How can I get the error to return: "The First Name field needs to be last least 1 character long."

Thank you for your attention.
Reply
#2

CodeIgniter 4 Validation Library - eithRequest()

SEE: how it's handaling error messages.
What did you Try? What did you Get? What did you Expect?

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

(This post was last modified: 11-20-2021, 08:17 AM by sevmusic.)

(11-19-2021, 03:25 AM)InsiteFX Wrote: CodeIgniter 4 Validation Library - eithRequest()

SEE: how it's handaling error messages.

I've scoured that page and I did not seeing anything on how to get the label to the Validation class.

But your direction gave me an idea which wasn't spelled out in the documents (some of us need real world examples beaten over our heads).

So here's the solution for anyone wanting it.

MyController.php
PHP Code:
$this->validation->setRules([
    'first_name' => [
        'label' => 'First Name',
        'rules' => 'myFieldCheck'
        'errors' => [
            'myFieldCheck' => 'The {field} field needs to be last least 1 character long.'
        ]
    ],
]); 

MyValidationRules.php
PHP Code:
class MyValidationRules
{
    public function myFieldCheck(string $strstring &$error null): bool
    
{
        if(!strlen(trim($str)) > 0){
           return false;
       } else {
            return true;
        }
    }


Thanks for the help!
Reply




Theme © iAndrew 2016 - Forum software by © MyBB