Help writing custom validator

Help writing custom validator

piq_pm_pjkpiq_pm_pjk Posts: 21Questions: 7Answers: 1

I've taken several shots at this one, but have failed. Can someone show me how to write a custom validator that will send an error if there is already a row in the database that matches the submitted combination of values for col1 and col2?

include "config.php";
include( "../DataTables-1.10.16/extensions/Editor-PHP-1.7.3/php/DataTables.php" );
use
    DataTables\Editor,
    DataTables\Editor\Field,
    DataTables\Editor\Format,
    DataTables\Editor\Join,
    DataTables\Editor\Validate;
    
$enD = Editor::inst( $db, 'table', 'id' )
    ->field(
        Field::inst( 'table.id' )->set(false),
        
        Field::inst( 'table.col1' )
            ->validator( 'Validate::notEmpty' ),
            
        Field::inst( 'table.col2' )
            ->validator( 'Validate::notEmpty' )
    )

    ->process( $_POST )
    ->data();
    echo json_encode( $enD );

Replies

  • hamlet1964hamlet1964 Posts: 43Questions: 8Answers: 1

    I use this:

    <?php
    
    // DataTables PHP library
    include( "../lib/DataTables.php" );
    
    // Alias Editor classes so they are easy to use
    use
        DataTables\Editor,
        DataTables\Editor\Field,
        DataTables\Editor\Format,
        DataTables\Editor\Mjoin,
        DataTables\Editor\Options,
        DataTables\Editor\Upload,
        DataTables\Editor\Validate,
        DataTables\Editor\ValidateOptions;
    
    // Build our Editor instance and process the data coming from _POST
    Editor::inst( $db, 'Words', 'WCount' )
        ->fields(
            Field::inst( 'Word' )
                ->validator( Validate::unique(
        ValidateOptions::inst()
          ->message( 'Duplicate Entry') ) ),
            Field::inst( 'Type'),
            Field::inst( 'Phonetic' ),
            Field::inst( 'Definition' )
        )
        ->process( $_POST )
        ->json();
    
  • colincolin Posts: 15,146Questions: 1Answers: 2,587

    Hi @hamlet1964 ,

    Is that last post of yours the solution, or is this still not working?

    Cheers,

    Colin

  • piq_pm_pjkpiq_pm_pjk Posts: 21Questions: 7Answers: 1

    Thanks for the response hamlet1964, but doesn't that only validate that the 'Word' field is unique? I would need it to validate that the record has a unique pair of 'Word' and 'Type' in your example.

    For example, if a record exists with 'Word' = a and 'Type' = b, validator would send the error message if the new entry had a and b, respectively. If they enter a and c, it would take the entry.

  • allanallan Posts: 61,743Questions: 1Answers: 10,111 Site admin

    See this thread which is asking the same question.

    Allan

This discussion has been closed.