0

I have a function to insert some values into a table, but before inserting I want to check if e-mail address it's right. If not, break the function and returns an error. Case true, go on.

case when _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$' = true 
then raise exception 'Incorrect email'

_email is the parameter of funcion. But it's not working. Should I use "IF" or other conditional?

0

2 Answers 2

2

CASE works, but IF seems more appropriate.
You have some pointless noise in the expression and I think you got the logic backwards: 'Incorrect email' should be triggered if _email does not match the pattern:

IF _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$'  -- drop the pointless "= true"
THEN  -- do nothing - I inverted the logic
ELSE RAISE EXCEPTION 'Incorrect email';
END IF;

The new ASSERT (Postgres 9.5+) would also work, but that's really meant for debugging:

ASSERT _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$', 'Incorrect email';
Sign up to request clarification or add additional context in comments.

1 Comment

Worked great. I'm using this way in my function. Thanks!
0

You should be able to use the case inside plpgsql. Obviously what you are trying to do can be done through if statement as well...

 case when _email ~ '^[^@\s]+@[^@\s]+(\.[^@\s]+)+$' = true then
           raise exception 'Incorrect email';
      else
           --proceed with insert
  end case;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.