Welcome Guest, Not a member yet? Register   Sign In
Let's share custom validation rules
#1

(This post was last modified: 09-29-2023, 03:39 AM by dgvirtual.)

I think it would be beneficial to share custom validation rules. So, I will post some of mine below.

They might not be very universal, but still useful.




Rule  for validation rule for Lithuanian personal idntification number (not properly localizable, but it is easy to add localization to $error and $error_msg strings)

PHP Code:
/** 
 * Codeigniter 4 validation rule for Lithuanian personal idntification number
 */ 

class CustomRules
{
    public function valid_lt_id($value, ?string &$error null): bool
    
{
        $valid true;
        $error_msg '';

        //check length/type
        if ($valid && (strlen($value) !== 11 || !is_numeric($value))) {
            $valid false;
            $error_msg 'length not equal to 11 numbers, or not all numbers';
        }

        $digits str_split($value);

        //check date for validity
        if ($valid) {
            if (in_array($digits[0], [12])) {
                $prefix '18';
            } elseif (in_array($digits[0], [34])) {
                $prefix '19';
            } elseif (in_array($digits[0], [56])) {
                $prefix '20';
            } else {
                $prefix '21';
            }

            $fullDate $prefix substr($value16);
            $dateFormat 'Ymd';

            // Create a DateTime object from the provided date string
            $date DateTime::createFromFormat($dateFormat$fullDate);

            // Check if the date is valid and the input format is correct
            $valid $date && $date->format($dateFormat) === ($fullDate);
            if (!$valid) {
                $error_msg 'wrong date inside number';
            }
        }

        // check date for not future
        if ($valid) {
            $valid $fullDate <= date('Ymd');

            if (!$valid) {
                $error_msg 'date in the future cannot be correct';
            }
        }

        // check control number
        if ($valid) {

            $last null;
            $s $digits[0] * $digits[1] * $digits[2] * 3
                
$digits[3] * $digits[4] * $digits[5] * 6
                
$digits[6] * $digits[7] * $digits[8] * 9
                
$digits[9] * 1;

            if (($s 11) !== 10) {
                $last $s 11;
            } else {
                $s $digits[0] * $digits[1] * $digits[2] * 
                    
$digits[3] * $digits[4] * $digits[5] * 
                    
$digits[6] * $digits[7] * $digits[8] * 
                    
$digits[9] * 3;

                if (($s 11) !== 10) {
                    $last $s 11;
                } else {
                    $last 0;
                }
            }

            $valid $digits[10] == $last;
            if (!$valid) {
                $error_msg 'wrong control number';
            }
        }

        //check if the order number is not zero, should never be
        if ($valid && (string) substr($value73) === '000') {
            $valid false;
            $error_msg 'wrong registration number';
        }

        if ($valid) {
            return true;
        }
        // $error = lang('myerrors.invalidCode');
        $error 'Lithuanian Personal Identification Number is not valid: ' 
            $error_msg;
        return false;
    }

==

Donatas G.
Reply
#2

(This post was last modified: 10-03-2023, 01:40 PM by dgvirtual.)

Another validation function checks if the supplied value is unique to a particular user; it presupposes that the user ID in a particular db table is saved in `user_id` field and that the current user id is saved in a session variable `$_SESSION['user_id']`; otherwise it is to be used much like the default `is_unique` validation rule:

PHP Code:
    'name' => [
            
'label' => 'Name',
            
'rules' => 'required|max_length[100]|is_unique_to_user[clients.name,id,{id}]',
        ], 

This rule presupposes that your language Validation will contain an array key-value pair something like this:

PHP Code:
'is_unique_to_user' => 'Field {field} should have a unique value.'

so, here is the function:

PHP Code:
    public function is_unique_to_user(?string $strstring $field, array $data): bool
    
{
        [$field$ignoreField$ignoreValue] = array_pad(
            explode(','$field),
            3,
            null
        
);

        sscanf($field'%[^.].%[^.]'$table$field);

        $row Database::connect($data['DBGroup'] ?? null)
            ->table($table)
            ->select('1')
            ->where('user_id'$_SESSION['user_id'])
            ->where($field$str)
            ->limit(1);

        if (
            ! empty($ignoreField) && ! empty($ignoreValue)
            && ! preg_match('/^\{(\w+)\}$/'$ignoreValue)
        ) {
            $row $row->where("{$ignoreField} !="$ignoreValue);
        }

        return $row->get()->getRow() === null;
    
==

Donatas G.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB