Validate an empty field

Validate an empty field

sdroulerssdroulers Posts: 43Questions: 14Answers: 0

Hi,

in the editor I have one field which can be filled with numeric values or left empty if needed.

For the numeric validation, clearly no problem, the following lines work fine:

Field::inst( 'FO_initial_stock' )
    ->validator( 'Validate::numeric' )

To my surprise if I leave the field empty I have the following message in the editor box:

Wasn't expecting that and in this post it says it should work !

Any helped very welcomed ! :)

Thanks,

Sébastien

Answers

  • rf1234rf1234 Posts: 3,000Questions: 87Answers: 421

    In the post you are quoting Allan says that the default is to allow a null value if it is optional. You need to define your SQL database field to allow null values if you want to do it like this. You probably defined the database field to be not null. If it is not null you must provide a valid integer. Null or space aren't valid integers.
    If you return space to the database it will not work even if you allow for null values.

    Looking at your variable name "initial_stock" you might not even need null values but rather a zero value.

    In that case you don't need to change the database field definition but simply return a zero in case the field is empty. If you don't want to display zero in the front end but rather an empty field combine it with a get formatter.

    Field::inst( 'FO_initial_stock' )
        ->validator( 'Validate::numeric' )
        ->setFormatter( function($val, $data, $opts) {
                        if ($val <= '') {
                            return 0;
                        } else {
                            return $val;
                        }
                    })
        ->getFormatter( function($val, $data, $opts) {
                       if ($val == 0) {
                            return '';
                        } else {
                            return $val;
                        }
                    }),
    
  • allanallan Posts: 63,523Questions: 1Answers: 10,473 Site admin

    I think this is probably a good use case for the nullEmpty or ifEmpty formatters. That's basically the same as rf1234's excellent reply, just with a little less custom logic since the format for this already exists.

    Allan

  • sdroulerssdroulers Posts: 43Questions: 14Answers: 0

    Many thanks to both of you, it fixed the issue like a charm !

    Sébastien

This discussion has been closed.