Skip to content

Instantly share code, notes, and snippets.

@alvinncx
Created September 7, 2019 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvinncx/2aa76cc719faf9ac127ff157c549b543 to your computer and use it in GitHub Desktop.
Save alvinncx/2aa76cc719faf9ac127ff157c549b543 to your computer and use it in GitHub Desktop.
Playing with Elm v0.19.0
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
-- Main
main =
Browser.sandbox {init = init, update = update, view = view}
-- Model
type alias Model =
{ name: String
, email: String
, validated: Bool
, error: Bool
, message: String
}
init : Model
init =
Model "" "" False False ""
-- Same thing
-- { name = ""
-- , email = ""
-- }
-- Update
type Msg
= Name String
| Email String
| Submit
update msg model =
case msg of
Name name ->
{ model | name = name, validated = False }
Email email ->
{ model | email = email, validated = False }
Submit ->
case doValidation model of
Err message ->
{ model | validated = True, message = message, error = True }
Ok message ->
{ model | validated = True, message = message, error = False }
-- View
view : Model -> Html Msg
view model =
Html.form [ onSubmit Submit ]
[ input [ type_ "text", value model.name, onInput Name ] []
, input [ type_ "email", value model.email, onInput Email ] []
, div [] [ text (model.name ++ model.email) ]
, input [ type_ "submit", value "Submit"] []
, formValidation model
]
formValidation model =
if model.validated then
if model.error then
div [ style "color" "red" ] [ text model.message ]
else
div [ style "color" "green"] [ text model.message ]
else
div [] []
doValidation model =
if model.email == "alvin@gmail.com" then
Err "email has been taken"
else
Ok "ok"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment