ozmat/elm-forms - version: 2.0.1

for more information visit the package's GitHub page

Package contains the following modules:

elm-forms

A library for building and validating Forms in Elm

Build Status

Motivation

There is no specific way of handling/validating forms in Elm. This library aims to provide an easy but flexible way of creating forms, validating them, handling the different message updates and building a whole business logic on top of them.

Here is a list of different features that we need when dealing with forms imo (and that the library actually implements) :

Plus, the library should also be :

A quick overview

Here are some parts of the first example : a basic form with three fields (two strings and one int) that creates an OtherModel

...

{- Model -}

init : ( Model, Cmd Msg )
init =
    ( Model (F.form myFormFields myFormValidate)
    , Cmd.none
    )


type alias Model =
    { myForm : F.Form String MyFormError OtherModel
    }

...

{- Form -}

type alias OtherModel =
    { firstName : String
    , lastName : String
    , referenceNumber : Int
    }


type MyFormError
    = EmptyString
    | NotInt


myFormFields : FF.Fields String
myFormFields =
    FF.fields
        [ ( "first-name", FF.input )
        , ( "last-name", FF.input )
        , ( "reference-number", FF.input )
        ]


myFormValidate : FV.Validate String MyFormError OtherModel
myFormValidate fields =
    FV.valid OtherModel
        |> FV.required fields "first-name" (FV.stringField <| FV.notEmpty EmptyString FV.success)
        |> FV.required fields "last-name" (FV.stringField <| FV.notEmpty EmptyString FV.success)
        |> FV.required fields "reference-number" (FV.stringField <| FV.int NotInt FV.success)

...

{- Msg/Update -}

type Msg
    = Form (FU.Msg String)

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Form formMsg ->
          { model | myForm = FU.updateForm formMsg model.myForm } ! []

...

{- View -}

inputText : String -> String -> Html Msg
inputText placeHolder fieldName =
    input
      [ inputStyle
      , placeholder placeHolder
      , onInput (FU.stringFieldMsg Form fieldName)
      ]
      []

...

F.validate model.myForm -- validates the form and returns a `FormResult`

A journey with Forms (examples)

For a better understanding on how to use the library, I would recommend you to go through all the examples, following the order specified. You should have a look at the source code, as there are some comments there, while running the examples and playing with them.

All the examples are single apps (and have their own elm-package.json), so you can run them like this :

cd EXAMPLE_DIR
elm-reactor

If you have downloaded/cloned the all library you can just :

cd elm-forms/examples
elm-reactor

and have access to all the examples.

Troubleshooting