Skip to content

Commit

Permalink
add domain name validation module
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Cady committed Jan 24, 2016
1 parent eab2150 commit faf9c1b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
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 (domainLiteral)
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 (domainLiteral <* endOfInput)

instance Show DomainName where
show = show . toByteString

instance Read DomainName where
readListPrec = Read.readListPrecDefault
readPrec = Read.parens (do
bs <- Read.readPrec
case parseOnly (domainLiteral <* 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
, domainLiteral
)
where

Expand Down

0 comments on commit faf9c1b

Please sign in to comment.