PHP Field Validator custom closure function parameters

PHP Field Validator custom closure function parameters

DralghazaliDralghazali Posts: 3Questions: 1Answers: 0

I have a use case where the Database schema is designed in a Data segregation prospect
with a lot of reference key constraint to insure data integrity, and using multiple LEFT JOINs to use them in a single Editor form.

so I have some tables where all of the Data is required, and other tables where the Data is optional according to the user category, but because of the reference key constraints Editor will return an "Integrity constraint violation error", because it will try to submit an empty field.

To work around this issue, I was thinking to make tow different Forms, with different server side scripts to handle this.

then I have come across the the documentation for the Field Validator custom function
and noticed in the website documentation that, the parameter are like:

Field::inst( 'last_name' )
    ->validator( function ( $val, $data, $field, $host ) {
        return strlen( $val ) > 50 ?
            'Name length must be 50 characters or less' :
            true;
    } );

form the example in the website https://editor.datatables.net/manual/php/validation#Custom-field-validators

and I was using an old parameters like:

Field::inst( 'engine' )->validator( function($val, $data, $opts) {
         if ( ! preg_match( '/^1/', $val ) ) {
           return "Value <b>must</b> start with a 1";
         }
         return true;
      } )

provided in the Validate class documentation.

the new parameters with "$field" parameter was very useful and solved my problem
as this return an instance of the field it self so I can make a "toggle" like effect with set(false) method
with the validator like this :

->validator(function ($val, $data, $field, $host) {
    if ($data['PaymentType'] !== '02') {
        $field->set(false);
        return true;
    }
    //some extra validation...
    return true;
})

so by this way it was possible to escape the integrity constraint violation error.
actually it works like a dependent field but on server side.

Hope this would be useful for someone with similar case.

Replies

  • allanallan Posts: 61,635Questions: 1Answers: 10,092 Site admin

    Thanks for posting this. Yes, the new API is much nicer (imho of course - although I wrote it... ;)). Good to hear it helped here for you.

    Regards,
    Allan

Sign In or Register to comment.