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

后端 未结 4 565
有刺的猬
有刺的猬 2020-12-25 12:02

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

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-25 12:42

    You can also create a domain and 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.

提交回复
热议问题