Validating with custom query

Validating with custom query

andrewbellandrewbell Posts: 12Questions: 3Answers: 0

Hello;

I am refactoring a legacy PHP IP management application to use DataTables with Editor. For one use case I have, the app currently validates an entered IP against two things - it cannot be within an already defined subnet, and it cannot be defined in an unrelated table.

The current SQL queries used in my legacy app are:

$sql = "SELECT id FROM sub_list WHERE inet_aton('{$_POST['ip']}') 
BETWEEN network and broadcast"; 
//sub_list is the table being edited, and _POST['ip]' is going to be the 
//field needing validation in Editor

$sql = "SELECT id FROM table2 WHERE ip = inet_aton('{$_POST['ip']}');
// table2 is an unrelated table of IP addresses

I know I have to write a custom validation function, but I can't figure out how to run these queries within it. I've looked at the API documentation, but it didn't help. In case it's not terribly obvious, I'm a sysadmin, not a developer.

Any pointers would be appreciated.

Replies

  • allanallan Posts: 61,665Questions: 1Answers: 10,096 Site admin

    Hi,

    As you say you will need custom validation. I think the key thing you are missing is how to run a custom query against the db:

    Field::inst( 'ip' )
        ->validator( function ( $val, $data, $field, $host ) use ($db) {
            $queryResult = $db->raw('SELECT ... FROM ... WHERE ...')->fetch();
            ...
        } );
    

    Allan

  • andrewbellandrewbell Posts: 12Questions: 3Answers: 0

    Yes, that was it. Thank you.

    Andrew

This discussion has been closed.