T-SQL: checking for email format

I tested the following query with many different wrong and valid email addresses. It should do the job.

IF (
     CHARINDEX(' ',LTRIM(RTRIM(@email_address))) = 0 
AND  LEFT(LTRIM(@email_address),1) <> '@' 
AND  RIGHT(RTRIM(@email_address),1) <> '.' 
AND  CHARINDEX('.',@email_address ,CHARINDEX('@',@email_address)) - CHARINDEX('@',@email_address ) > 1 
AND  LEN(LTRIM(RTRIM(@email_address ))) - LEN(REPLACE(LTRIM(RTRIM(@email_address)),'@','')) = 1 
AND  CHARINDEX('.',REVERSE(LTRIM(RTRIM(@email_address)))) >= 3 
AND  (CHARINDEX('.@',@email_address ) = 0 AND CHARINDEX('..',@email_address ) = 0)
)
   print 'valid email address'
ELSE
   print 'not valid'

It checks these conditions:

  • No embedded spaces
  • ‘@’ can’t be the first character of an email address
  • ‘.’ can’t be the last character of an email address
  • There must be a ‘.’ somewhere after ‘@’
  • the ‘@’ sign is allowed
  • Domain name should end with at least 2 character extension
  • can’t have patterns like ‘.@’ and ‘..’

Leave a Comment