QGIS – Setting Constraint for Not Null Depending on Another Field Value

constraintexpressionfields-attributesnullqgis

Does anyone know it is possible in QGIS to add a constraint to a field not to be null, only when another field has a certain value.

For example I have a field A that can be with value 'foo' or 'bar' and a field B with free text.
I want the field B to be not null (mandatory to fill), when field A is 'foo'.
But it can be empty when field A is 'bar'.

Hope I'm clear enough in my description.

Best Answer

On field B, for constraints use this expression:

case 
    when "field_A" = 'foo' then not (field_B is NULL) 
    when "field_A" <> 'foo' then field_B is NULL or field_B is not NULL 
end

enter image description here