Skip to content

Instantly share code, notes, and snippets.

@notyy
Last active July 21, 2019 17:46
Show Gist options
  • Save notyy/d2f9fb4087e26d42e450a956c51f054d to your computer and use it in GitHub Desktop.
Save notyy/d2f9fb4087e26d42e450a956c51f054d to your computer and use it in GitHub Desktop.
implement a submit button in elm form guide
import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (onInput, onClick)
import String exposing (length)
main =
Html.beginnerProgram
{ model = { name = "", password = "", passwordAgain = "", validationResult = NotDone }
, view = view
, update = update
}
-- MODEL
type alias Model =
{ name : String
, password : String
, passwordAgain : String
, validationResult : ValidationResult
}
type ValidationResult
= NotDone
| Error String
| ValidationOK
-- UPDATE
type Msg
= Name String
| Password String
| PasswordAgain String
| Submit
update : Msg -> Model -> Model
update action model =
case action of
Name name ->
{ model | name = name }
Password password ->
{ model | password = password }
PasswordAgain password ->
{ model | passwordAgain = password }
Submit ->
{ model | validationResult = validate model}
validate : Model -> ValidationResult
validate model =
if (String.length model.password) < 3 then
Error "Password length must be as least 3 chars long"
else if (model.password /= model.passwordAgain) then
Error "Passwords do not match!"
else
ValidationOK
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input [ type' "text", placeholder "Name", onInput Name ] []
, input [ type' "password", placeholder "Password", onInput Password ] []
, input [ type' "password", placeholder "Re-enter Password", onInput PasswordAgain ] []
, button [ onClick Submit ] [ text "submit" ]
, viewValidation model
]
viewValidation : Model -> Html msg
viewValidation model =
let
(color, message) =
case model.validationResult of
NotDone -> ("", "")
Error message -> ("red", message)
ValidationOK -> ("green", "OK")
in
div [ style [("color", color)] ] [ text message ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment