-
-
Save themaxhero/4f3a0edc706d5b8af8d8df33168a0d80 to your computer and use it in GitHub Desktop.
Simple Form
This file contains 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
import Html exposing (..) | |
import Html.Events exposing (..) | |
import Html.Attributes exposing (..) | |
import Random | |
main = | |
Html.program | |
{ init = init | |
, view = view | |
, update = update | |
, subscriptions = subscriptions | |
} | |
-- MODEL | |
type alias Model = | |
{ okay : Bool, | |
name : String, | |
error : Maybe String | |
} | |
init : (Model, Cmd Msg) | |
init = | |
({okay = False, name = "", error = Nothing }, Cmd.none) | |
-- UPDATE | |
type Msg | |
= ThrowError String | |
| Validate | |
| Write String | |
update : Msg -> Model -> (Model, Cmd Msg) | |
update msg model = | |
case msg of | |
Write str -> | |
let | |
model_ = | |
{model | name = str, okay = False } | |
in | |
(model_, Cmd.none) | |
ThrowError name -> | |
let | |
getErrorMsg msg = | |
case msg of | |
"hostname_invalid" -> | |
"hostname is invalid" | |
_ -> | |
"" | |
model_ = | |
{ model | name = model.name, error = Just <| getErrorMsg name, okay = False } | |
in | |
(model_, Cmd.none) | |
Validate -> | |
let | |
model_ = | |
{ model | name = model.name, error = Nothing, okay = True } | |
in | |
(model_, Cmd.none) | |
-- SUBSCRIPTIONS | |
subscriptions : Model -> Sub Msg | |
subscriptions model = | |
Sub.none | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
let | |
name_ = | |
case model.name of | |
"" -> | |
"" | |
_ -> | |
model.name | |
errorMsg = | |
case model.error of | |
Just error -> | |
True | |
Nothing -> | |
False | |
okayStyle = | |
style [("border","1px solid #00FF00")] | |
errorStyle = | |
style [("border","1px solid #FF0000")] | |
errorMsgStyle = | |
style [("color","#FF0000")] | |
getText str = | |
Write str | |
attr = | |
if model.okay && (not <| errorMsg) then | |
[ onInput <| getText | |
, onBlur <| Validate | |
, placeholder "hostname" | |
, value name_ | |
, okayStyle | |
] | |
else if (not <| model.okay) && errorMsg then | |
[ onBlur <| Validate | |
, onInput <| getText | |
, value name_ | |
, placeholder "hostname" | |
, errorStyle | |
] | |
else | |
[ onBlur <| Validate | |
, placeholder "hostname" | |
, onInput <| getText | |
] | |
errorElementMsg msg = | |
case msg of | |
Just str -> | |
span[errorMsgStyle][text str] | |
Nothing -> | |
span[][text ""] | |
in | |
div [] | |
[ br[][] | |
, br[][] | |
, br[][] | |
, input attr [] | |
, br[][] | |
, errorElementMsg model.error | |
, p[][] | |
, span[] | |
[ button [onClick Validate][text "Validate"] | |
, span[][text " "] | |
, button [onClick (ThrowError "hostname_invalid")][text "Throw error"] | |
] | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment