Skip to content

Instantly share code, notes, and snippets.

@pyk
Forked from james2doyle/valid-email.lua
Created March 9, 2017 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyk/af133a193953b0b98b0ae4912533c4a4 to your computer and use it in GitHub Desktop.
Save pyk/af133a193953b0b98b0ae4912533c4a4 to your computer and use it in GitHub Desktop.
Lua validate email address
function validemail(str)
if str == nil then return nil end
if (type(str) ~= 'string') then
error("Expected string")
return nil
end
local lastAt = str:find("[^%@]+$")
local localPart = str:sub(1, (lastAt - 2)) -- Returns the substring before '@' symbol
local domainPart = str:sub(lastAt, #str) -- Returns the substring after '@' symbol
-- we werent able to split the email properly
if localPart == nil then
return nil, "Local name is invalid"
end
if domainPart == nil then
return nil, "Domain is invalid"
end
-- local part is maxed at 64 characters
if #localPart > 64 then
return nil, "Local name must be less than 64 characters"
end
-- domains are maxed at 253 characters
if #domainPart > 253 then
return nil, "Domain must be less than 253 characters"
end
-- somthing is wrong
if lastAt >= 65 then
return nil, "Invalid @ symbol usage"
end
-- quotes are only allowed at the beginning of a the local name
local quotes = localPart:find("[\"]")
if type(quotes) == 'number' and quotes > 1 then
return nil, "Invalid usage of quotes"
end
-- no @ symbols allowed outside quotes
if localPart:find("%@+") and quotes == nil then
return nil, "Invalid @ symbol usage in local part"
end
-- only 1 period in succession allowed
if domainPart:find("%.%.") then
return nil, "Too many periods in domain"
end
-- just a general match
if not str:match('[%w]*[%p]*%@+[%w]*[%.]?[%w]*') then
return nil, "Email pattern test failed"
end
-- all our tests passed, so we are ok
return true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment