Welcome Guest, Not a member yet? Register   Sign In
Own validation rules with CodeIgniter >4.5
#1
Star 
(This post was last modified: 02-05-2025, 09:11 AM by minsk832.)

Based on the CodeIgniter documentation on validation, there are still a few things that are a bit unclear to me, so I wanted to ask here for advice on whether my approach is in line with best practice and how you would implement it.

https://codeigniter.com/user_guide/libra...ation.html

I have created a new class under app/Validation/NewsletterRules.php:

PHP Code:
<?php

namespace App\Validation;

class 
NewsletterRules
{
    // Validation rules
    public static $rules = [
        'email' => 'required|valid_email|max_length[254]|isNotTrashmail|hasValidMxRecord',
        //...
    ];

    private function getEmailHost(string $email): string
    
{
        $parts explode('@'$email);
        return strtolower(trim(end($parts)));
    }

    public function isNotTrashmail(string $str null, ?string &$error null): bool
    
{
        $trashmailFilePath WRITEPATH 'data/trashmails.txt';
        if (!file_exists($trashmailFilePath)) {
            return true;
        }

        $trashmailList file($trashmailFilePathFILE_IGNORE_NEW_LINES FILE_SKIP_EMPTY_LINES);
        $emailHost $this->getEmailHost($str);

        foreach ($trashmailList as $trashDomain) {
            if (stripos($emailHost$trashDomain) !== false) {
                $error 'Email provider not supported.';
                return false;
            }
        }

        return true;
    }

    public function hasValidMxRecord(string $str null, ?string &$error null): bool
    
{
        $host $this->getEmailHost($str);
        if (!checkdnsrr($host'MX')) {
            $error 'The domain does not have a valid DNS MX record.';
            return false;
        }
        return true;
    }


And registered them accordingly under app/Config/Validation.php:

PHP Code:
    public array $ruleSets = [
        //...,
        \App\Validation\NewsletterRules::class,
        //...
    ]; 

Now I would do the following in the controller:

PHP Code:
$validation service('validation');
$validation->setRules(\App\Validation\NewsletterRules::$rules);
if (
$validation->run($data)) {
    $validatedData $validation->getValidated();


Would this be the correct / best possible procedure? Are there more elegant ways? Do you prefer the validation rules in the controller or in the model? In general, most frameworks seem to leave the validation completely to the controller?

I am also a bit confused by the statement at $validation = service('validation'); What exactly does this mean? Isn't it used in the example itself?

Quote:"You may never need to use this method, as both the Controller and the Model provide methods to make validation even easier."


Thank you very much for your thoughts!
Reply


Messages In This Thread
Own validation rules with CodeIgniter >4.5 - by minsk832 - 02-05-2025, 09:08 AM



Theme © iAndrew 2016 - Forum software by © MyBB