/// Type-safe decoding and validation of HTML form data. A port of the Gleam /// package `formal` (hex.pm/packages/formal, Apache-2.0). /// /// import form /// /// pub type SignUp { /// SignUp(email: String, password: String) /// } /// /// /// A schema that decodes a `SignUp` from form data. /// fn signup_schema() -> form.Schema { /// use email <- form.field("email", form.parse_email()) /// use password <- form.field("password", { /// form.parse_string() /// |> form.check_string_length_more_than(7) /// }) /// use _ <- form.field("confirm", { /// form.parse_string() /// |> form.check_confirms(password) /// }) /// form.success(SignUp(email: email, password: password)) /// } /// /// A `Schema` describes how to decode a typed value from the key-value /// string pairs an HTML form produces. `new` turns it into a `Form`; add /// the submitted values (`add_values` takes `http.form_body(req)`'s list /// as it is) and `run` gives either the decoded value, or the form with /// errors attached, ready to re-render: /// /// fn handle_submission(values: List<(String, String)>) { /// match form.new(signup_schema()) |> form.add_values(values) |> form.run { /// Ok(signup) -> // ... use the SignUp value /// Error(f) -> // ... re-render, `form.field_error_messages(f, "email")` /// } /// } /// /// Parsers (`parse_*`) extract a value from a field's input and are /// _short-circuiting_: when one fails, the checks (`check_*`) chained after /// it don't run, so `parse_int() |> check_int_more_than(0)` on `"abc"` /// reports `[MustBeInt]`, nothing more. Checks don't short-circuit each /// other: every failed check adds its error. import std/float import std/list import std/result import std/string // ---- types ------------------------------------------------------------------- /// A form! Created from a `Schema` with the `new` function. /// /// Supply values to a form with the `add_*` functions and then pass it to the /// `run` function to get either the resulting value or any errors. /// /// Use the `language` function to supply a new translation function to change /// the language of the error messages returned by the `field_error_messages` /// function. The default language is `en_gb` English. pub opaque type Form { Form( translator: fn(FieldError) -> String , values: List<(String, String)> , errors: List<(String, List)> , run: RunFunction ) } type RunFunction = fn( List<(String, String)> , List<(String, List)> ) -> (model, List<(String, List)>) /// A description of how to decode a typed value from form data. This can be /// used to create a new form object using the `new` function. pub opaque type Schema { Schema(run: RunFunction) } /// Why a field failed to parse or validate; `en_gb` and `en_us` translate /// these into text for the user, or supply your own with `language`. @derive Eq Show Debug pub type FieldError { MustBePresent , MustBeInt , MustBeFloat , MustBeEmail , MustBePhoneNumber , MustBeColour , MustBeStringLengthMoreThan(limit: Int) , MustBeStringLengthLessThan(limit: Int) , MustBeIntMoreThan(limit: Int) , MustBeIntLessThan(limit: Int) , MustBeFloatMoreThan(limit: Float) , MustBeFloatLessThan(limit: Float) , MustBeAccepted /// For confirmation of passwords, etc. Must match the first field. , MustConfirm /// For values that must be unique, e.g. user email addresses. , MustBeUnique , CustomError(message: String) } /// A parser extracts a value from form values, converting it to a desired /// type and optionally validating the value. Parsers are used with the /// `field` function. /// /// See the `parse_*` and `check_*` functions for more information. /// /// Functions that start with `parse_*` are _short-circuiting_, so any parser /// functions that come afterwards will not be run. For example, given this /// code: /// /// form.parse_int() |> form.check_int_more_than(0) /// /// If the input is not an int then `parse_int` will fail, causing /// `check_int_more_than` not to run, so the errors will be `[MustBeInt]`. pub opaque type Parser { Parser( run: fn(List, CheckingStatus) -> (value, CheckingStatus, List) ) } type CheckingStatus { Check, DontCheck } // ---- forms ------------------------------------------------------------------- /// Create a new form from a schema. /// /// Add values to the form with the `add_*` functions and use `run` to get /// either the final value or some errors from the form and values. /// /// ## Example /// /// let schema = { /// use name <- form.field("name", { /// form.parse_string() |> form.check_not_empty /// }) /// use age <- form.field("age", form.parse_int()) /// form.success(Person(name: name, age: age)) /// } /// let f = form.new(schema) pub fn new :: schema: Schema -> Form { Form(translator: en_gb, values: [], errors: [], run: schema.run) } /// Supply a translation function that will be used when converting any /// `FieldError`s to text that can be presented to the user. /// /// Built-in languages: /// /// - `en_gb` /// - `en_us` /// /// These functions are named using the IETF language tag for the language /// they translate to. /// /// If no language is supplied then `en_gb` is used by default. pub fn language :: form: Form translator: fn(FieldError) -> String -> Form { Form(..form, translator: translator) } /// Get all the errors within a form. /// /// If `run` or `add_error` have not been called then there will be no errors. pub fn all_errors :: form: Form -> List<(String, List)> { form.errors } /// Get all the values within a form. pub fn all_values :: form: Form -> List<(String, String)> { form.values } /// Get all the values for a given form field. /// /// ## Examples /// /// let f = form.new(schema) /// |> form.add_int("one", 100) /// |> form.add_string("one", "Hello") /// |> form.add_string("two", "Hi!") /// form.field_values(f, "one") == ["Hello", "100"] pub fn field_values :: form: Form name: String -> List { values_of form.values name } /// Get the first value for a given form field. /// /// ## Examples /// /// let f = form.new(schema) |> form.add_int("one", 100) /// form.field_value(f, "one") == "100" /// form.field_value(f, "two") == "" pub fn field_value :: form: Form name: String -> String { match values_of form.values name { [first, ..] -> first, [] -> "" } } /// Run a form, returning either the successfully parsed value if there are /// no errors, or a new instance of the form with the errors added to the /// fields. pub fn run :: form: Form -> Result> { let (value, errors) = form.run form.values [] match errors { [] -> Ok(value), _ -> Error(Form(..form, errors: errors)) } } /// Add multiple values to a form. This function is useful for adding values /// from a HTTP request form body sent to your server, or from a HTML form /// element in your browser-based application. /// /// ## Example /// /// form.new(signup_schema()) /// |> form.add_values(http.form_body(req)) /// |> form.run pub fn add_values :: form: Form values: List<(String, String)> -> Form { Form(..form, values: list.append values form.values) } /// Replace any existing values of a form with new values. This function is /// useful for adding values from a HTTP request form body sent to your /// server, or from a HTML form element in your browser-based application. pub fn set_values :: form: Form values: List<(String, String)> -> Form { Form(..form, values: values) } /// Add a string value to the form. /// /// You may want to use this to pre-fill a form with some already-saved /// values for the user to edit. pub fn add_string :: form: Form field: String value: String -> Form { Form(..form, values: [(field, value), ..form.values]) } /// Add an int value to the form. /// /// You may want to use this to pre-fill a form with some already-saved /// values for the user to edit. pub fn add_int :: form: Form field: String value: Int -> Form { Form(..form, values: [(field, show value), ..form.values]) } /// Get the error messages for a field, if there are any. /// /// The text is formatted using the translator function given with the /// `language` function. The default translator is `en_gb`. pub fn field_error_messages :: form: Form name: String -> List { list.flat_map (errors_of form.errors name) fn errors { list.map errors form.translator } } /// Get all the form field errors. /// /// If the `run` function or the `add_error` function have not been called /// then the form is clean and won't have any errors yet. pub fn field_errors :: form: Form name: String -> List { flatten (errors_of form.errors name) } /// Add an error to one of the fields of the form. /// /// This function may be useful if you have some additional validation that /// runs outside of the form schema and you want to surface the error /// messages to the user via the form. pub fn add_error :: form: Form name: String error: FieldError -> Form { Form(..form, errors: [(name, [error]), ..form.errors]) } // The values of `name` in `pairs`, in order (gleam's `list.key_filter`). fn values_of :: pairs: List<(String, String)> name: String -> List { pairs |> list.filter fn pair { match pair { (key, _) -> key == name } } |> list.map fn pair { match pair { (_, value) -> value } } } // The error lists of `name` in `pairs`, in order. fn errors_of :: pairs: List<(String, List)> name: String -> List> { pairs |> list.filter fn pair { match pair { (key, _) -> key == name } } |> list.map fn pair { match pair { (_, errors) -> errors } } } fn flatten :: xss: List> -> List { list.fold xss [] fn acc xs { list.append acc xs } } // The first occurrence of each error, in order (gleam's `list.unique`). fn unique :: errors: List -> List { list.reverse ( list.fold errors [] fn acc error { if list.any acc fn seen { seen == error } { acc } else { [error, ..acc] } } ) } // ---- schemas ----------------------------------------------------------------- /// Add a new parser to the form for a given form field name. pub fn field :: name: String parser: Parser continuation: fn(value) -> Schema -> Schema { Schema( fn values errors { let input = values_of values name let (value, _status, new_errors) = parser.run input Check let errors = match new_errors { [] -> errors, _ -> [(name, new_errors), ..errors] } (continuation value).run values errors } ) } /// Finalise a schema, having successfully parsed a value. pub fn success :: value: model -> Schema { Schema(fn _ errors { (value, errors) }) } // ---- parsers ----------------------------------------------------------------- /// A parser that applies another parser to each input value in a list. /// /// Takes a parser for a single value and returns a parser that can handle /// multiple values of the same type. This is useful for form fields that /// can have multiple values, such as checkboxes, multi-selects, or just /// repeated inputs of other types. /// /// ## Example /// /// let schema = { /// use tags <- form.field("tag", form.parse_list(form.parse_string())) /// form.success(Article(tags: tags)) /// } /// /// This would parse multiple "tag" fields into a list of strings. pub fn parse_list :: parser: Parser -> Parser> { Parser( fn inputs check { let (values, status, errors) = list.fold inputs ([], Check, []) fn acc input { match acc { (values, _, errors) -> { let (value, status, new_errors) = parser.run [input] check ([value, ..values], status, [new_errors, ..errors]) } } } (list.reverse values, status, unique (flatten (list.reverse errors))) } ) } /// A parser that applies another parser if there is a non-empty-string /// input value for the field. /// /// ## Example /// /// let schema = { /// use age <- form.field("age", form.parse_optional(form.parse_int())) /// form.success(Person(age: age)) /// } /// /// This would parse an int if the form field has text in it, returning /// `None` otherwise. pub fn parse_optional :: parser: Parser -> Parser> { Parser( fn inputs check { if list.any inputs fn input { input != "" } { let (value, status, errors) = parser.run inputs check (Some(value), status, errors) } else { (None, check, []) } } ) } /// Parse a bool value from a checkbox type input. /// /// No value is `False`, while any value (including the empty string) counts /// as `True`. A checked checkbox input with no explicitly set value has the /// value `"on"`, which is `True`. Unchecked checkbox inputs send no value /// when the form is submitted: they are absent from the sent payload. /// /// ## Example /// /// let schema = { /// use agreed <- form.field("terms-and-conditions", { /// form.parse_checkbox() |> form.check_accepted /// }) /// form.success(Signup(agreed: agreed)) /// } pub fn parse_checkbox :: -> Parser { Parser( fn inputs status { match inputs { [] -> (False, status, []), _ -> (True, status, []) } } ) } /// Parse a string value. This parser can never fail! /// /// ## Example /// /// let schema = { /// use name <- form.field("name", { /// form.parse_string() |> form.check_not_empty /// }) /// form.success(Person(name: name)) /// } pub fn parse_string :: -> Parser { Parser( fn inputs status { match inputs { [input, ..] -> (input, status, []), [] -> ("", status, []) } } ) } /// A parser for a whole number. /// /// Returns a `MustBeInt` error if the input cannot be parsed as a valid int. /// /// ## Example /// /// let schema = { /// use age <- form.field("age", { /// form.parse_int() |> form.check_int_more_than(0) /// }) /// form.success(Person(age: age)) /// } pub fn parse_int :: -> Parser { Parser( fn inputs status { value_parser inputs 0 status MustBeInt string.to_int } ) } /// A parser for floating point numbers. /// /// Returns a `MustBeFloat` error if the input cannot be parsed as a float. /// /// ## Example /// /// let schema = { /// use price <- form.field("price", { /// form.parse_float() |> form.check_float_more_than(0.0) /// }) /// form.success(Product(price: price)) /// } pub fn parse_float :: -> Parser { Parser( fn inputs status { value_parser inputs 0.0 status MustBeFloat fn input { match float.parse input { Ok(number) -> Ok(number) , Error(_) -> result.map (string.to_int input) float.from_int } } } ) } /// A parser that validates email addresses. /// /// Performs basic email validation by checking for the presence of an "@" /// symbol. Returns a `MustBeEmail` error if the input is not a valid email /// format. /// /// ## Example /// /// let schema = { /// use email <- form.field("email", form.parse_email()) /// form.success(Person(email: email)) /// } pub fn parse_email :: -> Parser { Parser( fn inputs status { value_parser inputs "" status MustBeEmail fn input { if string.contains input "@" { Ok(input) } else { Error(()) } } } ) } /// A parser for phone numbers. /// /// Phone numbers are checked with these rules: /// - Must be between 8 and 15 digits after removing formatting /// - Must contain only digits after removing formatting characters /// - `+` may optionally be the first character. /// - `-`, ` `, `(`, and `)` are permitted, but are removed. /// /// Returns a `MustBePhoneNumber` error if the input doesn't satisfy these /// rules. /// /// ## Example /// /// let schema = { /// use phone <- form.field("phone", form.parse_phone_number()) /// form.success(Person(phone: phone)) /// } pub fn parse_phone_number :: -> Parser { Parser( fn inputs status { value_parser inputs "" status MustBePhoneNumber fn input { phone_number_loop (string.chars input) "" 0 } } ) } fn phone_number_loop :: input: List tel: String size: Int -> Result { match input { _ if size > 15 -> Error(()) , [] -> if size > 7 { Ok(tel) } else { Error(()) } , [ c , ..rest ] -> if c == "+" && tel == "" { phone_number_loop rest tel size } else if is_phone_separator c && tel != "" { phone_number_loop rest tel size } else if is_digit c { phone_number_loop rest (tel <> c) (size + 1) } else { Error(()) } } } fn is_phone_separator :: c: String -> Bool { c == "-" || c == "(" || c == ")" || c == " " } fn is_digit :: c: String -> Bool { string.contains "0123456789" c } /// A parser for colour values. /// /// Parses colour strings in HTML hex format (e.g. "#FF0000", "#00ff00") /// and returns the hex colour string. /// /// Returns a `MustBeColour` error if the input is not a valid hex colour. /// /// ## Example /// /// let schema = { /// use background <- form.field("background", form.parse_colour()) /// form.success(Theme(background: background)) /// } pub fn parse_colour :: -> Parser { Parser( fn inputs status { value_parser inputs "" status MustBeColour fn input { match string.chars input { ["#", a, b, c, d, e, f] -> if list.all [a, b, c, d, e, f] is_hex_digit { Ok(input) } else { Error(()) } , _ -> Error(()) } } } ) } fn is_hex_digit :: c: String -> Bool { string.contains "0123456789abcdefABCDEF" c } /// Create a custom parser for any type. /// /// If the parser function fails it must return two values: /// - A default "zero" value of the expected type. This will be used to run /// the remaining parser code, and then will be discarded. /// - An error message string to present to the user. /// /// ## Examples /// /// form.parse(fn(input) { /// match input { /// ["Squirtle", ..] -> Ok(Squirtle) /// , ["Bulbasaur", ..] -> Ok(Bulbasaur) /// , ["Charmander", ..] -> Ok(Charmander) /// , _ -> Error((Squirtle, "must be a starter Pokémon")) /// } /// }) /// /// ## Internationalisation /// /// If your application supports multiple languages you will need to ensure /// the error string returned by your parser function is already in the /// desired language. pub fn parse :: parser: fn(List) -> Result -> Parser { Parser( fn input status { match parser input { Ok(value) -> (value, status, []) , Error(pair) -> match pair { (zero, message) -> (zero, DontCheck, [CustomError(message)]) } } } ) } /// Convert the parsed value into another, similar to `list.map` or /// `result.map`. pub fn map :: parser: Parser mapper: fn(t1) -> t2 -> Parser { Parser( fn input status { let (value, new_status, errors) = parser.run input status (mapper value, new_status, errors) } ) } // Run `next` on the first input value; `zero` and `error` when there is no // input or `next` fails, skipping any checks chained after the parser. fn value_parser :: inputs: List zero: t status: CheckingStatus error: FieldError next: fn(String) -> Result -> (t, CheckingStatus, List) { match inputs { [input, ..] -> match next input { Ok(value) -> (value, status, []), Error(_) -> (zero, DontCheck, [error]) } , _ -> (zero, DontCheck, [error]) } } // ---- checks ------------------------------------------------------------------ /// Add a custom check to the parser. /// /// ## Examples /// /// let must_not_be_rude = fn(text) { /// if contains_swear_word(text) { /// Error("must not be rude") /// } else { /// Ok(text) /// } /// } /// let schema = { /// use name <- form.field("name", { /// form.parse_string() |> form.check(must_not_be_rude) /// }) /// form.success(Profile(name: name)) /// } /// /// ## Internationalisation /// /// If your application supports multiple languages you will need to ensure /// the error string returned by your checker function is already in the /// desired language. pub fn check :: parser: Parser checker: fn(b) -> Result -> Parser { add_check parser fn value { match checker value { Ok(v) -> Ok(v), Error(message) -> Error(CustomError(message)) } } } /// Ensure that the string value is not an empty string. pub fn check_not_empty :: parser: Parser -> Parser { add_check parser fn x { match x { "" -> Error(MustBePresent), _ -> Ok(x) } } } /// Ensure that an int is less than a specified limit. pub fn check_int_less_than :: parser: Parser limit: Int -> Parser { add_check parser fn x { if x < limit { Ok(x) } else { Error(MustBeIntLessThan(limit)) } } } /// Ensure that an int is more than a specified limit. pub fn check_int_more_than :: parser: Parser limit: Int -> Parser { add_check parser fn x { if x > limit { Ok(x) } else { Error(MustBeIntMoreThan(limit)) } } } /// Ensure that a string is more than a specified length. pub fn check_string_length_more_than :: parser: Parser limit: Int -> Parser { add_check parser fn x { if string.length x > limit { Ok(x) } else { Error(MustBeStringLengthMoreThan(limit)) } } } /// Ensure that a string is less than a specified length. pub fn check_string_length_less_than :: parser: Parser limit: Int -> Parser { add_check parser fn x { if string.length x < limit { Ok(x) } else { Error(MustBeStringLengthLessThan(limit)) } } } /// Ensure that a float is more than a specified limit. pub fn check_float_more_than :: parser: Parser limit: Float -> Parser { add_check parser fn x { if x > limit { Ok(x) } else { Error(MustBeFloatMoreThan(limit)) } } } /// Ensure that a float is less than a specified limit. pub fn check_float_less_than :: parser: Parser limit: Float -> Parser { add_check parser fn x { if x < limit { Ok(x) } else { Error(MustBeFloatLessThan(limit)) } } } /// Ensure that a bool is `True`. pub fn check_accepted :: parser: Parser -> Parser { add_check parser fn x { match x { True -> Ok(x), False -> Error(MustBeAccepted) } } } /// Ensure that a field equals some other value. Useful for password /// confirmation. /// /// ## Example /// /// let schema = { /// use password <- form.field("password", { /// form.parse_string() |> form.check_string_length_more_than(8) /// }) /// use _ <- form.field("password-confirmation", { /// form.parse_string() |> form.check_confirms(password) /// }) /// form.success(User(password: password)) /// } pub fn check_confirms :: parser: Parser other: t -> Parser where Eq { add_check parser fn x { if x == other { Ok(x) } else { Error(MustConfirm) } } } fn add_check :: parser: Parser checker: fn(b) -> Result -> Parser { Parser( fn inputs status { let (value, new_status, errors) = parser.run inputs status let errors = match new_status { Check -> match checker value { Error(error) -> [error, ..errors], Ok(_) -> errors } , DontCheck -> errors } (value, new_status, errors) } ) } // ---- translations -------------------------------------------------------------- /// Translates `FieldError`s into strings suitable for showing to the user. /// /// ## Examples /// /// form.en_gb(MustBeColour) == "must be a hex colour code" pub fn en_gb :: error: FieldError -> String { match error { MustBeAccepted -> "must be accepted" , MustBeColour -> "must be a hex colour code" , MustBeEmail -> "must be an email" , MustBeFloat -> "must be a number" , MustBeFloatLessThan(limit) -> "must be less than {limit}" , MustBeFloatMoreThan(limit) -> "must be more than {limit}" , MustBeInt -> "must be a whole number" , MustBeIntLessThan(limit) -> "must be less than {limit}" , MustBeIntMoreThan(limit) -> "must be more than {limit}" , MustBePhoneNumber -> "must be a phone number" , MustBePresent -> "must not be blank" , MustBeStringLengthLessThan(limit) -> "must be less than {limit} characters" , MustBeStringLengthMoreThan(limit) -> "must be more than {limit} characters" , MustConfirm -> "doesn't match" , MustBeUnique -> "is already in use" , CustomError(message) -> message } } /// Translates `FieldError`s into strings suitable for showing to the user. /// /// The same as `en_gb`, but with Americanised spelling of the word "color". /// /// ## Examples /// /// form.en_us(MustBeColour) == "must be a hex color code" pub fn en_us :: error: FieldError -> String { match error { MustBeColour -> "must be a hex color code", _ -> en_gb error } }