-
-
Save haphaeu/f2e7169161d68f09fe434bbf02cc150a to your computer and use it in GitHub Desktop.
implement a submit button in elm form guide
This file contains hidden or 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 Browser | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Html.Events exposing (onInput, onClick) | |
-- MAIN | |
main = | |
Browser.sandbox { init = init, update = update, view = view } | |
-- MODEL | |
type alias Model = | |
{ name : String | |
, age : String | |
, password : String | |
, passwordAgain : String | |
, validationResult : ValidationResult | |
} | |
type ValidationResult = | |
NotDone | |
| Error String | |
| ValidationOK | |
init : Model | |
init = | |
Model "" "" "" "" NotDone | |
-- UPDATE | |
type Msg | |
= Name String | |
| Age String | |
| Password String | |
| PasswordAgain String | |
| Submit | |
update : Msg -> Model -> Model | |
update msg model = | |
case msg of | |
Name name -> | |
{ model | name = name } | |
Age age -> | |
{ model | age = age } | |
Password password -> | |
{ model | password = password } | |
PasswordAgain password -> | |
{ model | passwordAgain = password } | |
Submit -> | |
{ model | validationResult = validate model } | |
validate : Model -> ValidationResult | |
validate model = | |
if not (String.all Char.isDigit model.age) then | |
Error "Age must be numeric" | |
else if not (model.password == model.passwordAgain) then | |
Error "Passwords do not match!" | |
else if (String.length model.password) < 8 then | |
Error "Password length must be longer than 8." | |
else if not (String.any Char.isDigit model.password) then | |
Error "Password must contain numbers." | |
else if not (String.any Char.isUpper model.password && | |
String.any Char.isLower model.password) then | |
Error "Password must contain lower and upper case letters." | |
else | |
ValidationOK | |
-- VIEW | |
view : Model -> Html Msg | |
view model = | |
div [] | |
[ input [ type_ "text", placeholder "Name", onInput Name ] [] | |
, input [ type_ "text", placeholder "Age", onInput Age ] [] | |
, 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, msg) = | |
case model.validationResult of | |
NotDone -> ("", "") | |
Error message -> ("red", message) | |
ValidationOK -> ("green", "OK") | |
in | |
div [ style "color" color ] [ text msg ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment