Packages

A convention-first web framework for Gleam

Current section

Files

Jump to
refrakt src refrakt@validate.erl
Raw

src/refrakt@validate.erl

-module(refrakt@validate).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/refrakt/validate.gleam").
-export([required/4, min_length/5, max_length/5, inclusion/5, format/5]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-file("src/refrakt/validate.gleam", 20).
?DOC(" Check that a string value is not empty (after trimming whitespace).\n").
-spec required(list({binary(), binary()}), binary(), binary(), binary()) -> list({binary(),
binary()}).
required(Errors, Value, Field, Message) ->
case gleam@string:is_empty(gleam@string:trim(Value)) of
true ->
[{Field, Message} | Errors];
false ->
Errors
end.
-file("src/refrakt/validate.gleam", 34).
?DOC(
" Check that a string value has at least `min` characters.\n"
" Skips the check if the field already has an error (avoids duplicate messages).\n"
).
-spec min_length(
list({binary(), binary()}),
binary(),
binary(),
integer(),
binary()
) -> list({binary(), binary()}).
min_length(Errors, Value, Field, Min, Message) ->
case gleam@list:any(Errors, fun(E) -> erlang:element(1, E) =:= Field end) of
true ->
Errors;
false ->
case string:length(gleam@string:trim(Value)) < Min of
true ->
[{Field, Message} | Errors];
false ->
Errors
end
end.
-file("src/refrakt/validate.gleam", 53).
?DOC(
" Check that a string value has at most `max` characters.\n"
" Skips the check if the field already has an error.\n"
).
-spec max_length(
list({binary(), binary()}),
binary(),
binary(),
integer(),
binary()
) -> list({binary(), binary()}).
max_length(Errors, Value, Field, Max, Message) ->
case gleam@list:any(Errors, fun(E) -> erlang:element(1, E) =:= Field end) of
true ->
Errors;
false ->
case string:length(gleam@string:trim(Value)) > Max of
true ->
[{Field, Message} | Errors];
false ->
Errors
end
end.
-file("src/refrakt/validate.gleam", 71).
?DOC(" Check that a string value matches one of the allowed values.\n").
-spec inclusion(
list({binary(), binary()}),
binary(),
binary(),
list(binary()),
binary()
) -> list({binary(), binary()}).
inclusion(Errors, Value, Field, Allowed, Message) ->
case gleam@list:contains(Allowed, Value) of
true ->
Errors;
false ->
[{Field, Message} | Errors]
end.
-file("src/refrakt/validate.gleam", 85).
?DOC(" Check that a string value matches a format predicate.\n").
-spec format(
list({binary(), binary()}),
binary(),
binary(),
fun((binary()) -> boolean()),
binary()
) -> list({binary(), binary()}).
format(Errors, Value, Field, Predicate, Message) ->
case Predicate(Value) of
true ->
Errors;
false ->
[{Field, Message} | Errors]
end.