I'm new to regex and I'm using Postgres. I'm trying to make a check constraint in a table so that any data into some column always checks for only alphanumeric, numeric, alphanumeric without spaces, etc.
For example, given a table like:
CREATE TABLE client (
PRIMARY KEY (id),
id CHAR(18) NOT NULL,
name TEXT NOT NULL,
promo_code TEXT NOT NULL
);
I'd like to make a constraint with a CHECK that only allows alphanumeric without spaces content in id, alphabetic with spaces in name, alphanumeric with symbols without spaces content in promo_code. id has a strict length of 18, but name and promo_code have variable length.
Would something like the following work?
ALTER TABLE client
ADD CONSTRAINT ck_client_one
CHECK (
id ~ '%\w%' AND id !~ '%\s%',
name ~ '%\w%' AND name !~ '%\d%',
promo_code ~ '%\w%' OR promo_code ~ '%\W%' AND promo_code !~ '%\s%'
);
ALTER TABLE client
ADD CONSTRAINT ck_client_two
CHECK (
id ~ '%^[a-zA-Z0-9]*%' AND id !~ '%\s%',
name ~ '%^[a-zA-Z]*%',
promo_code ~ '%^[a-zA-Z0-9]*%' OR promo_code !~ '%^[a-zA-Z0-9]*%'
AND promo_code !~ '%\s%'
);
rd_nielsen
ALTER TABLE client
ADD CONSTRAINT ck_client_one
CHECK (
id ~ '.+\w+.+' AND id !~ '.+\s+.+',
name ~ '.+\w+.+' AND name !~ '.+\d+.+',
promo_code ~ '.+\w+.+' OR promo_code ~ '.+\W+.+'
AND promo_code !~ '.+\s+.+'
);
Thanks!