Last active
July 22, 2021 18:14
-
-
Save james2doyle/67846afd05335822c149 to your computer and use it in GitHub Desktop.
Lua validate email address
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validemail(str) | |
if str == nil or str:len() == 0 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 or not domainPart:find("%.") then | |
return nil, "Domain is invalid" | |
end | |
if string.sub(domainPart, 1, 1) == "." then | |
return nil, "First character in domain cannot be a dot" | |
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 | |
-- no dot found in domain name | |
if not domainPart:find("%.") then | |
return nil, "No TLD found in domain" | |
end | |
-- only 1 period in succession allowed | |
if domainPart:find("%.%.") then | |
return nil, "Too many periods in domain" | |
end | |
if localPart:find("%.%.") then | |
return nil, "Too many periods in local part" | |
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 |
The program will stop if string is empty ""
So, I added str:len checker:
if str:len() == 0 then return nil end
One more thing. This code will accept "@gmail.com" but it shouldn't accept it ?
Added a bunch of checks from all the suggestions. Thanks everyone
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found another error. This string validates:
[email protected]
Add this check:
if string.sub(domainPart, 1, 1) == "." then
return false, "first character in domainPart is a dot"
end