5

I want to disallow the use of spaces in some text/varchar fields.

Even more, it would be best to have only a set of characters that are allowed to use there, like:

[a-zA-Z0-9_\-]

And I want to make it as a rule to all VARCHAR fields that are members of primary key in their tables.

This should be done on the database level and could throw an exception when trying to insert a wrong record or update one with a change of a key field to invalid value.

Can this be done within the database level? Should I use Pl/Perl for that, or is there any simpler method?

3 Answers 3

8

You don't even need stored procedures:

alter table xxx add constraint check_valid_chars check ( your_column ~ '^[a-zA-Z0-9_\-]+$' );

should work.

Sign up to request clarification or add additional context in comments.

5 Comments

Ok. Any way to automate this for N tables, each with 1+ fields to be altered? like: for each table { for each field in table that is a key { alter } }
requires scripting but the key to your task is in the information_schema.
Check my blogpost on "grantall" : depesz.com/index.php/2007/10/19/grantall - the technique I used there can be applied in this case as well.
I just used your_column !~ ' '.
I believe that won't account for other blank space characters, like Tabs and Carriage Returns
4

You can define a domain, look at http://www.postgresql.org/docs/current/interactive/sql-createdomain.html at the bottom, there is an example about US postal code.

2 Comments

This looks promising, but it requires altering all my existing data, which is quite a lot of tables. I was thinking more of a way to inject into my existing database, that's why I thought of a trigger and function first.
this does NOT require altering all your data, only schema. DOMAINs are designed precisely for this. ALTER TABLE foo ALTER bar TYPE my_domain;
0

Seeing your latest comment you could perhaps use CHECK constraints and regex search? But you will have to modify the schema (tables) and insert it for each field.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.