Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a constraint to check if an email is valid in postgres?

Tags:

postgresql

How can I create a constraint to use a regular expression in postgres?

like image 708
nunos Avatar asked Apr 16 '11 21:04

nunos


People also ask

How do I use constraints in PostgreSQL?

A check constraint is the most generic constraint type. It allows you to specify that the value in a certain column must satisfy a Boolean (truth-value) expression. For instance, to require positive product prices, you could use: CREATE TABLE products ( product_no integer, name text, price numeric CHECK (price > 0) );

What is check constraint in PostgreSQL?

The PostgreSQL CHECK constraint controls the value of a column(s) being inserted. The PostgreSQL provides the CHECK constraint, which allows the user to define a condition, that a value entered into a table, has to satisfy before it can be accepted.


2 Answers

CREATE TABLE emails (     email varchar     CONSTRAINT proper_email CHECK (email ~* '^[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$') ); 

(regex may be incomplete, you can search for regexp for email matching all over the web and pick the one you like best).

like image 86
Michael Krelin - hacker Avatar answered Sep 23 '22 15:09

Michael Krelin - hacker


I recommend using an existing email address parsing module instead of making up your own pattern matching. For example:

CREATE OR REPLACE FUNCTION check_email(email text) RETURNS bool LANGUAGE plperlu AS $$ use Email::Address;  my @addresses = Email::Address->parse($_[0]); return scalar(@addresses) > 0 ? 1 : 0; $$;  CREATE TABLE emails (     email varchar     CONSTRAINT proper_email CHECK (check_email(email)) ); 
like image 24
Peter Eisentraut Avatar answered Sep 23 '22 15:09

Peter Eisentraut