-
Notifications
You must be signed in to change notification settings - Fork 0
/
SignupForm.elm
108 lines (93 loc) · 3.09 KB
/
SignupForm.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
module SignupForm exposing (..)
import Html.App
import Html exposing (..)
import Html.Events exposing (..)
import Html.Attributes exposing (id, type', for, value, class)
import Http
import Task exposing (Task)
import Json.Decode exposing (succeed)
view model =
form [ id "signup-form" ]
[ h1 [] [ text "Signup Form" ]
, label [ for "username-field" ] [ text "username: " ]
, input
[ id "username-field"
, type' "text"
, value model.username
, onInput (\str -> { msgType = "SET_USERNAME", payload = str })
]
[]
, div [ class "validation-error" ] [ text (viewUsernameErrors model) ]
, label [ for "password" ] [ text "password: " ]
, input
[ id "password-field"
, type' "password"
, value model.password
, onInput (\str -> { msgType = "SET_PASSWORD", payload = str })
]
[]
, div [ class "validation-error" ] [ text model.errors.password ]
, div [ class "signup-button", onClick { msgType = "VALIDATE", payload = "" } ] [ text "Sign Up!" ]
]
viewUsernameErrors model =
if model.errors.usernameTaken then
"That username is taken!"
else
model.errors.username
getErrors model =
{ username =
if model.username == "" then
"Please enter a username!"
else
""
, usernameTaken = model.errors.usernameTaken
, password =
if model.password == "" then
"Please enter a password!"
else
""
}
update msg model =
if msg.msgType == "VALIDATE" then
let
url =
"https://api.github.com/users/" ++ model.username
failureToMsg err =
{ msgType = "USERNAME_AVAILABLE", payload = "" }
successToMsg result =
{ msgType = "USERNAME_TAKEN", payload = "" }
request =
Http.get (succeed "") url
cmd =
Task.perform failureToMsg successToMsg request
in
( { model | errors = getErrors model }, cmd )
else if msg.msgType == "USERNAME_TAKEN" then
( withUsernameTaken True model, Cmd.none )
else if msg.msgType == "USERNAME_AVAILABLE" then
( withUsernameTaken False model, Cmd.none )
else if msg.msgType == "SET_USERNAME" then
( { model | username = msg.payload }, Cmd.none )
else if msg.msgType == "SET_PASSWORD" then
( { model | password = msg.payload }, Cmd.none )
else
( model, Cmd.none )
withUsernameTaken isTaken model =
let
currentErrors =
model.errors
newErrors =
{ currentErrors | usernameTaken = isTaken }
in
{ model | errors = newErrors }
initialErrors =
{ username = "", password = "", usernameTaken = False }
initialModel =
{ username = "", password = "", errors = initialErrors }
main =
Html.App.program
{ init = ( initialModel, Cmd.none )
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}