Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added domain name validation module #15

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions email-validate.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ library
hs-source-dirs: src
exposed-modules:
Text.Email.Validate,
Text.Domain.Validate,
Text.Email.Parser

Test-Suite Main
Expand Down
53 changes: 53 additions & 0 deletions src/Text/Domain/Validate.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
module Text.Domain.Validate
( isValid
, validate
, domainName
, DomainName
, toByteString
)
where

import Control.Applicative ((<*))

import Data.Attoparsec.ByteString (endOfInput, parseOnly)
import Data.ByteString (ByteString)

import Data.Data (Data, Typeable)
import GHC.Generics (Generic)
import Text.Email.Parser (dottedAtoms)
import qualified Text.Read as Read


-- | Represents a domain name.
data DomainName = DomainName ByteString
deriving (Eq, Ord, Data, Typeable, Generic)

-- | Smart constructor for a domain name
domainName :: ByteString -> Maybe DomainName
domainName = either (const Nothing) Just . validate

-- | Validates whether a particular string is a domain name
-- according to RFC5322.
isValid :: ByteString -> Bool
isValid = either (const False) (const True) . validate

-- | If you want to find out *why* a particular string is not
-- a domain name, use this.

validate :: ByteString -> Either String DomainName
validate = fmap DomainName . parseOnly (dottedAtoms <* endOfInput)

instance Show DomainName where
show = show . toByteString

instance Read DomainName where
readListPrec = Read.readListPrecDefault
readPrec = Read.parens (do
bs <- Read.readPrec
case parseOnly (dottedAtoms <* endOfInput) bs of
Left _ -> Read.pfail
Right a -> return $ DomainName a)

-- | Converts an email address back to a ByteString
toByteString :: DomainName -> ByteString
toByteString (DomainName d) = d
1 change: 1 addition & 0 deletions src/Text/Email/Parser.hs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ module Text.Email.Parser
, EmailAddress
, unsafeEmailAddress
, toByteString
, dottedAtoms
)
where

Expand Down