postgresql 如何创建约束以检查电子邮件在 postgres 中是否有效?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5689718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I create a constraint to check if an email is valid in postgres?
提问by nunos
How can I create a constraint to use a regular expression in postgres?
如何创建约束以在 postgres 中使用正则表达式?
回答by Michael Krelin - hacker
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).
(regex 可能不完整,您可以在整个网络上搜索 regexp 以匹配电子邮件,然后选择您最喜欢的那个)。
回答by Peter Eisentraut
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))
);
回答by Gajus
You can also create a domainand use it as a type when defining table columns, e.g.
您还可以创建一个域并将其用作定义表列时的类型,例如
CREATE DOMAIN email AS TEXT CHECK (VALUE ~* '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$');
CREATE TABLE emails (
email email
);
This way you will not need to redefine the regex every time an email containing columns is used in the database.
这样,每次在数据库中使用包含列的电子邮件时,您都不需要重新定义正则表达式。