formz/validation
Functions
pub fn and(
previous: fn(a) -> Result(b, String),
next: fn(b) -> Result(c, String),
) -> fn(a) -> Result(c, String)
Chain validations together.
Examples
let is_even = fn(num) {
case num % 2 == 0 {
True -> Ok(num)
False -> Error("must be even")
}
}
let check = and(int, is_even)
check("2")
# -> Ok(2)
check("hi")
# -> Error("must be a whole number")
check("1")
# -> Error("must be even")
pub fn email(input: String) -> Result(String, String)
Parse the input as a String that looks like an email address, i.e. it
contains an @
character, with at least one other character on either
side
(this behavior more closely matches what the browser does than just
checking for an @
).
Examples
email("hello@example.com")
# -> Ok("hello@example.com")
email("@")
# -> Error("Must be an email address")
email("hello")
# -> Error("Must be an email address")
pub fn int(str: String) -> Result(Int, String)
Parse the input as an int.
Examples
int("1")
# -> Ok(1)
int("3.4")
# -> Error("Must be a whole number")
int("hello")
# -> Error("Must be a whole number")
pub fn list_item_by_index(
variants: List(a),
) -> fn(String) -> Result(a, String)
Validates that the input is one from a list of allowed values. Takes a list of Gleam values that can be chosen. This uses the index of the item in to find the desired value.
Examples
enum(["One","Two","Three"])("1")
# -> Ok("Two")
enum([True, False])("42")
# -> Error("must be an item in list")
enum([True, False])("ok")
# -> Error("must be an item in list")
pub fn non_empty_string(str: String) -> Result(String, String)
Trim and leave the input as it is, but verify it is non-empty.
non_empty_string("hello")
# -> Ok("hello")
non_empty_string(" ")
# -> Error("is required")
pub fn number(str: String) -> Result(Float, String)
Parse the input as a float. this is forgiving and will also parse ints into floats.
Examples
number("1")
# -> Ok(1.0)
number("3.4")
# -> Ok(3.4)
number("hello")
# -> Error("Must be a number")
pub fn on(val: String) -> Result(Bool, String)
Parse the input as a boolean, where only “on” is True and allowed.
All other values are an error. This is useful for HTML checkboxes, which
the browser sends the empty string if unchecked, and "on"
if checked.
Examples
on("on")
# -> Ok(True)
on("")
# -> Error("is required")
on("hi")
# -> Error("is required")
pub fn replace_error(
previous: fn(a) -> Result(b, String),
error: String,
) -> fn(a) -> Result(b, String)
Replace the error message of a validation with a new one. Most of the built-in error messages are pretty rudimentary.