4

Is there, with QGIS 3, any way to restrict the data added to a specific field of a GeoPackage layer?

I want to restrict the data in a field of an attribute table with something like that:

2letters(a-z)-3letters(a-z)-2numbers(0-9)

2 Answers 2

6

Go to Layer Properties -> Attributes Form and then select your field; under Constraints use the relevant expression and check 'Enforce expression constraint'. This will restrict data input to the format you've described.

However, it's only applicable to the data in that project with those attribute form settings (which can be copied and pasted as part of the style) - it's not tied to the data; you'd need a constraint in your database for that.

enter image description here

Constraint checking in the form (wrong input triggers highlight, and doesn't allow saving due to the 'Enforce expression constraint' option selected earlier)

enter image description here

enter image description here

As for expressions, your best bet is using regexp_match().

Assuming your format is:

two lowercase letters, dash, three lowercase letters, dash, two numbers

Try the following expression (replace "test" with your field name)

regexp_match("test", '^[a-z]{2}-[a-z]{3}-[0-9]{2}$')
2

I didn't try but if you go in the Attributes Form panel of the layer properties you can set edit widget for your field, when you choose the text edit widget there is the option to set constraints by expression. I guess that using some expression in here will let you set the constraint you want.


References:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.