GithubHelp home page GithubHelp logo

dynajoe / elm-form Goto Github PK

View Code? Open in Web Editor NEW

This project forked from etaque/elm-form

0.0 1.0 0.0 270 KB

Forms handling in Elm

Home Page: http://package.elm-lang.org/packages/etaque/elm-form/latest

License: BSD 3-Clause "New" or "Revised" License

HTML 0.96% Elm 99.04%

elm-form's Introduction

Elm Form

HTML live forms builders and validation for Elm. Build Status

elm package install etaque/elm-form

For when the classical "a message per field" doesn't work well for you, at the price of loosing some typesafety.

Features

  • Validation API similar to Json.Decode with the standard map, andThen, etc: you either get the desired output value or all field errors
  • HTML inputs helpers with pre-wired handlers for live validation
  • Suite of basic validations, with a way to add your own
  • Unlimited fields, see andMap function (as in Json.Extra)
  • Nested fields (foo.bar.baz) and lists (todos.1.checked) enabling rich form build

See complete example here (source code).

Basic usage

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


-- your expected form output

type alias Foo =
    { bar : String
    , baz : Bool
    }


-- Add form to your model and msgs

type alias Model =
    { form : Form () Foo }

type Msg
    = NoOp
    | FormMsg Form.Msg


-- Setup form validation

init : ( Model, Cmd Msg )
init =
    ( { form = Form.initial [] validation }, Cmd.none )

validation : Validation () Foo
validation =
    map2 Foo
        (field "bar" email)
        (field "baz" bool)


-- 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 validation formMsg form }, Cmd.none )


-- Render form with Input helpers

view : Model -> Html Msg
view { form } =
    Html.map FormMsg (formView form)

formView : Form () Foo -> 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
        bar =
            Form.getFieldAsString "bar" form

        baz =
            Form.getFieldAsBool "baz" form
    in
        div []
            [ label [] [ text "Bar" ]
            , Input.textInput bar []
            , errorFor bar
            , label []
                [ Input.checkboxInput baz []
                , text "Baz"
                ]
            , errorFor baz
            , button
                [ onClick Form.Submit ]
                [ text "Submit" ]
            ]


app =
    Html.program
        { init = init
        , update = update
        , view = view
        , subscriptions = \_ -> Sub.none
        }

Advanced usage

Custom inputs

  • For rendering, Form.getFieldAsString/Bool provides a FieldState record with all required fields (see package doc).

  • For event handling, see all field related messages in Form.Msg type.

Overall, having a look at current helpers source code should give you a good idea of the thing.

Incremental validation

Similar to what Json.Extra provides. Use Form.apply, or the |: infix version from infix package:

Form.succeed Player
    |> andMap (field "email" (string |> andThen email))
    |> andMap (field "power" int)

Nested records

  • Validation:
validation =
    map2 Player
        (field "email" (string |> andThen email))
        (field "power" (int |> andThen (minInt 0)))
        (field "options"
            (map2 Options
                (field "foo" string)
                (field "bar" string)
            )
        )
  • View:
Input.textInput (Form.getFieldAsString "options.foo" form) []

Dynamic lists

-- model
type alias TodoList =
    { title : String
    , items : List String
    }

-- validation
validation : Validation () Issue
validation =
    map2 TodoList
        (field "title" string)
        (field "items" (list string))

-- view
formView : Form () Issue -> Html Form.Msg
formView form =
    div
        [ class "todo-list" ]
        [ Input.textInput
            (Form.getFieldAsString "title" form)
            [ placeholder "Title" ]
        , div [ class "items" ] <|
            List.map
                (itemView form)
                (Form.getListIndexes "items" form)
        , button
            [ class "add"
            , onClick (Form.Append "items")
            ]
            [ text "Add" ]
        ]

itemView : Form () Issue -> Int -> Html Form.Msg
itemView form i =
    div
        [ class "item" ]
        [ Input.textInput
            (Form.getFieldAsString ("items." ++ (toString i)) form)
            []
        , a
            [ class "remove"
            , onClick (Form.RemoveItem "items" i)
            ]
            [ text "Remove" ]
        ]

Initial values and reset

  • At form initialization:
import Form.Field as Field


initialFields : List ( String, Field )
initialFields =
    [ ( "power", Field.string "10" )
    , ( "options"
      , Field.group
            [ ( "foo", Field.string "blah" )
            , ( "bar", Field.string "meh" )
            ]
      )
    ]


initialForm : Form
initialForm =
    Form.initial initialFields validation

See Form.Field type for more options.

  • On demand:
button [ onClick (Form.Reset initialFields) ] [ text "Reset" ]

Note: To have programmatically control over any input[type=text]/textarea value, like reseting or changing the value, you must set the value attribute with Maybe.withDefault "" state.value, as seen here. There's a downside of doing this: if the user types too fast, the caret can go crazy.

More info: evancz/elm-html#81 (comment)

Custom errors

type LocalError = Fatal | NotSoBad

validation : Validation LocalError Foo
validation =
    (field "foo" (string |> customError Fatal))

-- creates `Form.Error.CustomError Fatal`

Async validation

This package doesn't provide anything special for async validation, but doesn't prevent you to do that neither. As field values are accessible from update with Form.getStringAt/getBoolAt, you can process them as you need, trigger effects like an HTTP request, and then add any errors to the view by yourself.

Another way would be to enable dynamic validation reload, to make it dependant of an effect, as it's part of the form state. Please ping me if this feature would be useful to you.

elm-form's People

Contributors

amitaibu avatar dimbleby avatar etaque avatar janjelinek avatar knuton avatar matsrietdijk avatar pablohirafuji avatar paparga avatar simonh1000 avatar soenkehahn avatar thomasweiser avatar thsoft avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.