Validate Unique if numeric, and not unique when value is "EXTRA"

Validate Unique if numeric, and not unique when value is "EXTRA"

ztevieztevie Posts: 101Questions: 23Answers: 5

Hi, here's a tough one for you:

I have a field which normally is numeric and must be unique when it is. But, on some occasions the user can create a record where the field value is set to "EXTRA".
Is it possible to validate:
1. Unique if it's a number.
2. If it's not a number the string must be exactly "EXTRA". But the value EXTRA needn't be unique.

I mean the Editor validation on the pphp side...

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,365Questions: 39Answers: 395

    You should create a custom validation method. Example in the docs.
    https://editor.datatables.net/manual/php/validation

  • ztevieztevie Posts: 101Questions: 23Answers: 5

    Yes, I know about the custom validators.
    But to emulate Unique I need to do my own check against the database. I was thinking the Unique method is so convenient...
    The best would be to use a custom validation where if the value is numeric, the unique validation steps in, and if not, the value must be EXTRA. But I don't think it's possible to nest validate methods within custom validation functions.

  • allanallan Posts: 63,836Questions: 1Answers: 10,518 Site admin
    Answer ✓

    I think in this case would would indeed need to create a custom validator. You can chain validation, but they must all pass and the unique validation wouldn't pass for the "extra" case.

    Allan

  • ztevieztevie Posts: 101Questions: 23Answers: 5
    edited January 2017

    I did a custom validation by calling an outside function. Here's how in case someone else need it in the future. The value can not be changed when Edit row, so I just need it on Create:


    //The Editor Field Field::inst( 'holes.hole_nr' ) ->validator( 'Validate::notEmpty', array( "message" => "The field can not be empty..." )) ->validator( 'Validate::noTags', array( "message" => "The field contains values not permitted..." )) ->validator( 'Validate::xss', array( "message" => "Xss warning..." )) ->validator( function ( $val, $data, $opts ) { return validateHoleNr($val); } ), //The function function validateHoleNr($v){ if ( isset( $_POST['action'] ) && $_POST['action'] === 'create' ) { if(ctype_digit($v)){ $db2 = new MysqliDb(Host, DBUserID, DBUserPassword, DBName); $db2->where ("hole_nr", $v); $db2->where ("blast_id", getBlastId()); $cnt = $db2->getValue ("holes", "count(hole_id)"); return $cnt > 0 ? 'The number already exists, choose another one' : true; } else{ return $v !== "EXTRA" ? "Please enter a valid number or EXTRA..." : true; } } else{ return true; } }
This discussion has been closed.