Email Validation Function

>>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,”)
END
–Check to see if “@” exists.
SET @atPos = charindex(‘@’,@email,1)
IF @atPos = 0
SET @valid = 0
–Check 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

Get the Free Newsletter!

Subscribe to Cloud Insider for top news, trends & analysis

Latest Articles