Skip to content

Instantly share code, notes, and snippets.

@pyar6329
Forked from moonlightdrive/password.elm
Created June 15, 2018 05:35
Show Gist options
  • Save pyar6329/2407ff7a42f752ced0c7cb7a23abf685 to your computer and use it in GitHub Desktop.
Save pyar6329/2407ff7a42f752ced0c7cb7a23abf685 to your computer and use it in GitHub Desktop.
Password Validation Exercises from the Elm Architecture Tutorial
{- Implementation of the Exercises for the Forms section of the Elm Architecture Tut
- http://guide.elm-lang.org/architecture/user_input/forms.html
-
- Elm Platform 0.17.1
-}
import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (onInput, onClick)
import String
import Char exposing (isDigit, isUpper, isLower)
main =
Html.beginnerProgram { model = model
, view = view
, update = update }
type Validation
= None
| Ok
| Error String
type alias Model =
{ name : String
, password : String
, pwAgain : String
, age : String
, valid : Validation
}
model : Model
model =
{ name = ""
, password = ""
, pwAgain = ""
, age = ""
, valid = None
}
type Msg
= Name String
| Password String
| PwAgain String
| Age String
| Check
update : Msg -> Model -> Model
update msg model =
case msg of
Name name ->
{ model | name = name }
Password password ->
{ model | password = password }
PwAgain pwAgain ->
{ model | pwAgain = pwAgain }
Age age ->
{ model | age = age }
Check ->
{ model | valid = validate model }
-- this fn disgusts me
validate : Model -> Validation
validate model =
if model.password /= model.pwAgain then Error "Passwords don't match"
else if String.length model.password < 8 then Error "Password must be 8 characters or more"
else if not (String.any isDigit model.password) then Error "Password must contain digits"
else if not (String.any isUpper model.password) then Error "Password must contain uppercase"
else if not (String.any isLower model.password) then Error "Password must contain lowercase"
else if String.length model.age == 0 then Error "Enter age"
else if not (String.all isDigit model.age) then Error "Age must be a number"
else Ok
-- Html Msg is a chunk of html that can product msg vals!
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 PwAgain ] []
, input [ type' "text", placeholder "Age", onInput Age ] []
, button [ onClick Check ] [ text "Submit" ]
, viewValidation model
]
viewValidation : Model -> Html Msg
viewValidation model =
let
(color, message) =
case model.valid of
Ok -> ("green", "OK")
Error err -> ("red", err)
None -> ("black", "Enter your details")
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