I have a shapefile in which I want to allow only numbers in a table field. For this I have inserted the following expression in Properties > Attribute Form> Constraints (see Screenshot). not regexp_match(s_nr,'[^0-9]') I also checked that the checkbox "Enforce constraint option" is checked. The expression works as desired and shows an orange cross when entering letters in the form, but when I try to save, it saves despite the set restrictions. our company uses 3rd party software that expects a string field at this point, so changing to integer-type isn't an option.

How can I prevent it from saving?

enter image description here

  • 4
    You probably use a string-type field. If you use integer-type field, your issue will be solved. Commented Mar 25, 2022 at 10:56
  • Thank you, this would of course be the better way, but our company uses 3rd party software that expects a string field at this point.
    – Omegon
    Commented Mar 25, 2022 at 12:26
  • As per the help center please do not include chit chat like thanks within your posts.
    – PolyGeo
    Commented Mar 25, 2022 at 18:08
  • 1
    The text field requirement is very relevant, you should add it to your question.
    – Berend
    Commented Mar 25, 2022 at 19:18
  • 2
    I did try with QGIS 3.24.1 (with the same setting and same constraints expression as you) and it work (ie. when I try to enter letters I got the orange cross (same as you) but the "OK" is disabled and I can't save)
    – J.R
    Commented Mar 29, 2022 at 9:57

2 Answers 2


Use this expression to define a constraint for the content of your field in the sense that it can only contain numbers, but it must be formatted as string:

to_string (to_int ("s_nr"))


As you say the field must contain numbers only. So convert the field's content to a number, using to_int() (integer) or to_real() (real number). So the expression will fail if the field contains anything elso but digits and you have your constraint defined.

But as you say for certain reasons, the field has to be of type text/string. So simply convert the number from above back to a string.


Easier than defining constaints is to simply create your attribute as a numerical field type. Then the constraint is inherent in the field-type and no one can enter anything but a number.

To still have the value at hand in string/text form for further processing, create a virtual field of Text (string) type that converts the numerical field to a string using the expression to_string ("numerical_field").

As a virtual field, it is dynamic and will be updated every time you change something in "numerical_field".

enter image description here

Your Answer

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

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