-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEmail.elm
42 lines (33 loc) · 911 Bytes
/
Email.elm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module Email exposing
( Email -- <= Doesn't expose constructor! Only type.
, EmailError(..)
, create
, unwrap
)
import Regex
import Regex exposing (regex)
import Result exposing (Result(..))
type Email = Email String
type EmailError =
InvalidChars
| NoDomain
unwrap : Email -> String
unwrap (Email address) =
address
-- Only way to construct an Email.
-- Which means you have to handle the Result, in
-- case the Email is wrong.
create : String -> Result EmailError Email
create str =
let
check err rx = boolToResult err (Regex.contains (regex rx))
in
(Ok str)
|> Result.andThen (check InvalidChars "^[\\w@+_.-]+$")
|> Result.andThen (check NoDomain "^[^@]+@[^@]+$")
|> Result.andThen (\str -> Ok (Email str))
boolToResult : e -> (r -> Bool) -> r -> Result e r
boolToResult failure predicate val =
if predicate val
then Ok val
else Err failure