iodevs / elm-validate / Transformation

This module helps to transform validated forms to models.

Helpers

withField : (a -> Result String b) -> (form -> Validation.Field raw a) -> Transformer (b -> c) form -> Transformer c form

This function is used to check if the given variable in the form has correct validity and if yes, then returns this variable with her value. Otherwise returns an Err errorMessage.

import Validation exposing (Field, preValidatedField)

type A
    = A Int

type B
    = B Float

type alias Model =
    { a : A, b : B }

type alias Form =
    { a : Field String Int, b : Field String Float }

form =
    Form (preValidatedField String.fromInt 1) (preValidatedField String.fromFloat 0.3)

condPosInt : Int -> Result String A
condPosInt val =
    if val > 0 then
        Ok (A val)

    else
        Err "Value must be positive number!!!"

condFloatRange : Float -> Result String B
condFloatRange val =
    if val < 10 && val > 0 then
        Ok (B val)

    else
        Err "Value isn't in range!!!"

model : Result String Model
model =
    toModel
        Model
        (withField condPosInt .a
            >> withField condFloatRange .b
        )
        form


-- Ok { a = 1, b = 0.3 }

withoutField : (a -> Result String b) -> (form -> a) -> Transformer (b -> c) form -> Transformer c form

This function is similar to function above and is used for non-field type of variables.

import Validation exposing (Field, preValidatedField)

type Planet
    = Venus
    | Earth
    | Mars

type alias Model =
    { planet : Planet, a : Int, b : Float }

type alias Form =
    { planet : Planet, a : Field String Int, b : Field String Float }

form =
    Form Earth (preValidatedField String.fromInt 1) (preValidatedField String.fromFloat 0.3)


--form = Form Mars (preValidatedField String.fromInt 1) (Validation.field "40.5")
model : Result String Model
model =
    let
        fieldOk =
            withField Ok

        valueOk =
            withoutField Ok
    in
    toModel
        Model
        (valueOk .planet
            >> fieldOk .a
            >> fieldOk .b
        )
        form


-- Ok { planet = Earth, a = 1, b = 0.3 }
-- for form with Mars we get:
--      Err "Form is not validated!",
-- because validity of initial value b is NotValidated.

toModel : model -> (Transformer model form -> Transformer data form) -> form -> Result String data

This function transforms form to model and returns an Err errorMessage if any variable in the form is NotValidated either Invalid. Otherwise returns Ok model. See examples above.