Postgres Function to Validate Email Address

前端 未结 6 2099
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 09:30

A check constraint which would call a function to validate email addresses is not working fine for me.

CREATE OR REPLACE FUNCTION f_IsValidEmail(text) return         


        
6条回答
  •  鱼传尺愫
    2021-01-02 09:51

    A bunch of these answers are close to the right way. These are the points for my submission.

    • You want to use a domain -- NOT the rule system.
    • You do NOT want to validate these email addresses with a regex. (Update Mar 2017: not really true anymore)

    I show two methods of how to do this the right on DBA.StackExchange.com. Both to check for the MX-record, and also using the HTML5 spec. Here is the short and sweet.

    CREATE EXTENSION citext;
    CREATE DOMAIN email AS citext
      CHECK ( value ~ '^[a-zA-Z0-9.!#$%&''*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$' );
    
    SELECT 'foobar@bar.com'::email;
    SELECT CAST('foobar@bar.com' AS email);
    

    For more information I highly suggest you read the answer in full. In the answer, I also show how you create a DOMAIN over Email::Valid, and explain why I no longer use that method.

提交回复
热议问题