Email Validation Function | Database Journal

Email Validation Function

Oct 9, 2003
1 minute read

>>Script Language and Platform: MSSQL
This function checks for invalid characters, and some basic format.
Since SQL can’t use regular expressions, it cannot do a thorough validation, but this function DOES handle the minimum.
If the email is valid, it returns 1, if not 0.

*ex.
This is to delete invalid emails

DELETE FROM address
WHERE master.dbo.EMAILVALIDATE(email) = 0

Author: Jimmy Hattori

CREATE FUNCTION EMAILVALIDATE (@email varChar(100))
RETURNS int
AS
BEGIN
DECLARE @invalChars varchar(5),@valid int,@badChar varchar(1),@atPos
int,@periodPos int
SET @valid = 1
SET @invalChars =/:,;’
–Check to see if it’s blank
IF len(ltrim(rtrim(@email))) = 0
   SET @valid = 0
ELSE
  	–Loop invalid characters to see if it exists in email
	WHILE len(@invalChars) > 0
	   BEGIN
		SET @badChar = substring(@invalChars,1,1)
		IF(charindex(@badChar,@email) > 0)
		   –If invalid character was found, return 0 to invalidate
		   SET @valid = 0
		SET @invalChars = replace(@invalChars,@badChar,”)
	   ENDCheck to see if “@” exists.
	SET @atPos = charindex(‘@’,@email,1)
	IF @atPos = 0
	   SET @valid = 0Check to see if extra “@” exists after 1st “@”.
	IF charindex(‘@’,@email,@atPos+1) > 0
	   SET @valid = 0
	SET @periodPos = charindex(‘.’,@email,@atPos)
	IF @periodPos = 0
	   SET @valid = 0
	IF (@periodPos+3) > len(@email)
	   SET @valid = 0
	RETURN (@valid)
END



Disclaimer:
We hope that the information on these script pages is
valuable to you. Your use of the information contained in these pages,
however, is at your sole risk. All information on these pages is provided
“as -is”, without any warranty, whether express or implied, of its accuracy,
completeness, or fitness for a particular purpose…

Disclaimer Continued

Back to Database Journal Home

Database Journal Logo

DatabaseJournal.com publishes relevant, up-to-date and pragmatic articles on the use of database hardware and management tools and serves as a forum for professional knowledge about proprietary, open source and cloud-based databases--foundational technology for all IT systems. We publish insightful articles about new products, best practices and trends; readers help each other out on various database questions and problems. Database management systems (DBMS) and database security processes are also key areas of focus at DatabaseJournal.com.

Property of TechnologyAdvice. © 2026 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.