Welcome Guest, Not a member yet? Register   Sign In
Custom Validation doesn't work?
#1

Hi, I want to create custom validation rule but it not working.

Config/Validation

Code:
    public function test_validate(string $str, string &$error = null): bool
    {
        $error = 'test error';
        return false;
    }

App\Model
Code:
    protected $validationRules = array(
        'name'     => 'required|test_validate'
    );

Result
Quote:CodeIgniter\Validation\Exceptions\ValidationException

{0} is not a valid rule.

For additional question, can someone give simpler example how to send parameters to the function? I don't get the 'require_with' example.
https://codeigniter4.github.io/CodeIgnit...-parameter

The new validation system is hard to understand compared to the previous callback system.
Reply
#2

(This post was last modified: 12-07-2018, 06:50 AM by donpwinston.)

The way I did it:

Config/Validation.php
PHP Code:
/**
     * Stores the classes that contain the
     * rules that are available.
     *
     * @var array
     */
    
public $ruleSets = [
        \
CodeIgniter\Validation\Rules::class,
        \
CodeIgniter\Validation\FormatRules::class,
        \
CodeIgniter\Validation\FileRules::class,
        \
CodeIgniter\Validation\CreditCardRules::class,
        \
App\Validation\MyRules::class
    ]; 


Application/Validation/MyRules.php

PHP Code:
<?php namespace App\Validation;

class 
MyRules
{
    public function 
valid_login(string $emailstring $field, array $data): bool
    
{
        
$db = new \App\Libraries\NcrsEbnDb();
        
$hashed_password $db->getPassword(trim($email));
        if (
$hashed_password == '')
            return 
false;
        else
            return 
password_verify(trim($data[$field]), $hashed_password);
    }

    public function 
valid_password(string $passwordstring $field, array $data): bool
    
{
        
$db = new \App\Libraries\NcrsEbnDb();
        
$hashed_password $db->getPassword(trim($data[$field]));
        if (
$hashed_password == '')
            return 
false;
        else
            return 
password_verify(trim($password), $hashed_password);
    } 



..etc
Simpler is always better
Reply
#3

Looks like you forgot to add it to the $ruleSets in Config/Validation.
Reply
#4

(This post was last modified: 12-09-2018, 07:50 PM by sibiniv.)

Thanks for the reply. So the function needs to be put in different file?
I thought it was supposed to be placed below this line

Code:
    //--------------------------------------------------------------------
    // Rules
    //--------------------------------------------------------------------
Reply
#5

You create a class whose member functions are your rules. Specify the class in the $ruleSets in Config/Validation.php.
Simpler is always better
Reply




Theme © iAndrew 2016 - Forum software by © MyBB