Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Main exposing (..)
- import Html exposing (..)
- import Html.Attributes exposing (..)
- import Html.Events exposing (..)
- import Form exposing (Form)
- import Form.Validate as Validate exposing (..)
- import Form.Input as Input
- type alias User =
- { name : String
- , password : String
- , passwordConfirmation : String
- }
- type alias Model =
- { form : Form String User }
- type Msg
- = NoOp
- | FormMsg Form.Msg
- init : ( Model, Cmd Msg )
- init =
- ( { form = Form.initial [] validate }, Cmd.none )
- validate : Validation String User
- validate =
- succeed User
- |> andMap (field "name" (string |> withCustomError "Input Name !"))
- |> andMap (field "password" (string |> withCustomError "Input Password!"))
- |> andMap ((field "password" string) |> andThen validateConfirmation)
- validateConfirmation : String -> Validation String String
- validateConfirmation password =
- field "passwordConfirmation"
- (string
- |> andThen
- (\confirmation ->
- if password == confirmation then
- succeed confirmation
- else
- fail (customError "Confirmation Error")
- )
- )
- -- Forward form msgs to Form.update
- update : Msg -> Model -> ( Model, Cmd Msg )
- update msg ({ form } as model) =
- case msg of
- NoOp ->
- ( model, Cmd.none )
- FormMsg formMsg ->
- ( { model | form = Form.update validate formMsg form }, Cmd.none )
- -- Render form with Input helpers
- view : Model -> Html Msg
- view { form } =
- Html.map FormMsg (formView form)
- formView : Form String User -> Html Form.Msg
- formView form =
- let
- -- error presenter
- errorFor field =
- case field.liveError of
- Just error ->
- -- replace toString with your own translations
- div [ class "error" ] [ text (toString error) ]
- Nothing ->
- text ""
- -- fields states
- name =
- Form.getFieldAsString "name" form
- password =
- Form.getFieldAsString "password" form
- passwordConfirmation =
- Form.getFieldAsString "passwordConfirmation" form
- in
- div []
- [ div []
- [ label [] [ text "Name" ]
- , Input.textInput name []
- , errorFor name
- ]
- , div []
- [ label [] [ text "Password" ]
- , Input.textInput password []
- , errorFor password
- ]
- , div []
- [ label [] [ text "Password Confirmation" ]
- , Input.textInput passwordConfirmation []
- , errorFor passwordConfirmation
- ]
- , button
- [ onClick Form.Submit ]
- [ text "Submit" ]
- ]
- main =
- Html.program
- { init = init
- , update = update
- , view = view
- , subscriptions = \_ -> Sub.none
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement