Skip to content

Instantly share code, notes, and snippets.

@cabe56
Created September 17, 2017 06:46
Show Gist options
  • Save cabe56/9c7f4b872122a38c073a3511bad2f60e to your computer and use it in GitHub Desktop.
Save cabe56/9c7f4b872122a38c073a3511bad2f60e to your computer and use it in GitHub Desktop.
An Introduction to Elm - Form
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (onInput, onClick)
import Char exposing (..)
import Tuple exposing (first, second)
main =
Html.beginnerProgram
{ model = model
, view = view
, update = update
}
-- MODEL
type alias Model =
{ name : String
, password : String
, passwordAgain : String
, age : String
, validationMessage : String
, validationColor : String
}
model : Model
model = Model "" "" "" "" "" "green"
-- UPDATE
type Msg
= Name String
| Password String
| PasswordAgain String
| Age String
| Submit
update : Msg -> Model -> Model
update msg model =
case msg of
Name name ->
{ model | name = name }
Password password ->
{ model | password = password }
PasswordAgain password ->
{ model | passwordAgain = password }
Age int ->
{ model | age = int }
Submit ->
{ model |
validationColor = first (colorAndMessage model),
validationMessage = second (colorAndMessage model) }
-- 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 ] []
, input [ type_ "number", placeholder "Age", onInput Age ] []
, button [ onClick Submit ] [ text "submit" ]
, validationSection model
]
validationSection : Model -> Html Msg
validationSection model =
let (color, message) =
(model.validationColor, model.validationMessage)
in
div [style [("color", color)]] [text message]
colorAndMessage : Model -> (String, String)
colorAndMessage model =
if String.length model.password < 8 then
("red", "Password must be at least 8 chars")
else if not (passesSecurityCheck model.password) then
("red", "Password must have at least one upper, one lower and one digit")
else if not (ageIsValid model.age) then
("red", "Age must be an int")
else if model.password /= model.passwordAgain then
("red", "Passwords do not match!")
else
("green", "OK")
ageIsValid : String -> Bool
ageIsValid age =
String.length age > 0 && (String.all Char.isDigit age)
passesSecurityCheck : String -> Bool
passesSecurityCheck str =
String.any Char.isUpper str &&
String.any Char.isLower str &&
String.any Char.isDigit str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment