How can I create a constraint to check if an email is valid in postgres?
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).
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))
);