简体   繁体   中英

How to use regex with PostgreSQL to Constrain a Columns input as alpha-numeric

I am attempting to create a constraint on a table that will ensure that a columns input is alpha-numerical ( eventually wishing to add a constraint that will prevent certain inputs based on the context type)

The following code does not seem to work because the regexp_matches() function needs to return a boolean . How would I go about using Regex in a column constraint so it returns a boolean value for CHECK .

CREATE TABLE contexts (
  id INT PRIMARY KEY,
  name VARCHAR NOT NULL,
  short_name VARCHAR NOT NULL,
  context_type VARCHAR REFERENCES context_types ON DELETE RESTRICT,
  context_status VARCHAR REFERENCES context_statuses ON DELETE RESTRICT,
  parent_id INT REFERENCES contexts ON DELETE CASCADE,

  CONSTRAINT CK_name CHECK (regexp_matches(name, '[a-zA-Z0-9]*')),
  CONSTRAINT CK_short_name CHECK (regexp_matches(short_name, '[a-zA-Z0-9]*'))
);

.

[SOLVED] As the answer I have shows that the best way to use regex with CHECK is to use the Regular Expression Match Operators ( mentioned in this documentation -- see section 9.7.3)

I suppose you want just use regex match operator ~ without returning captured group. So your query would be like this:

CREATE TABLE contexts (
  id INT PRIMARY KEY,
  name VARCHAR NOT NULL,
  short_name VARCHAR NOT NULL,
  context_type VARCHAR REFERENCES context_types ON DELETE RESTRICT,
  context_status VARCHAR REFERENCES context_statuses ON DELETE RESTRICT,
  parent_id INT REFERENCES contexts ON DELETE CASCADE,

  CONSTRAINT CK_name CHECK (name ~ '^[a-zA-Z0-9]*$'),
  CONSTRAINT CK_short_name CHECK (short_name ~ '^[a-zA-Z0-9]*$')
);

I have added ^$ to your regular expression as a whole line value should meet the regular expressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM