litmus v1.0.1 Litmus.Type.String View Source
This type validates and converts values to strings It converts boolean and number values to strings.
Options
:default
- Setting:default
will populate a field with the provided value, assuming that it is not present already. If a field already has a value present, it will not be altered.:min_length
- Specifies the minimum number of characters allowed in the string. Allowed values are non-negative integers.:max_length
- Specifies the maximum number of characters allowed in the string. Allowed values are non-negative integers.:length
- Specifies the exact number of characters allowed in the string. Allowed values are non-negative integers.:regex
- Specifies a Regular expression that a string must match. Use theLitmus.Type.String.Regex
struct with the options::pattern
- ARegex.t()
to match:error_message
- An error message to use when the pattern does not match
:replace
- Replaces occurences of a pattern with a string. Use theLitmus.Type.String.Replace
struct with the options::pattern
- ARegex.t()
,String.t()
, or compiled pattern to match:replacement
- AString.t()
to replace:global
- Whentrue
, all occurences of the pattern are replaced. Whenfalse
, only the first occurence is replaced. Defaults totrue
.
:required
- Setting:required
totrue
will cause a validation error when a field is not present or the value isnil
. Allowed values for required aretrue
andfalse
. The default isfalse
.:trim
- Removes additional whitespace at the front and end of a string. Allowed values aretrue
andfalse
. The default isfalse
.
Examples
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> min_length: 3,
...> max_length: 10,
...> trim: true
...> },
...> "password" => %Litmus.Type.String{
...> length: 6,
...> regex: %Litmus.Type.String.Regex{
...> pattern: ~r/^[a-zA-Z0-9_]*$/,
...> error_message: "password must be alphanumeric"
...> }
...> }
...> }
iex> params = %{"username" => " user123 ", "password" => "root01"}
iex> Litmus.validate(params, schema)
{:ok, %{"username" => "user123", "password" => "root01"}}
iex> Litmus.validate(%{"password" => "ro!_@1"}, schema)
{:error, "password must be alphanumeric"}
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> replace: %Litmus.Type.String.Replace{
...> pattern: ~r/_/,
...> replacement: ""
...> }
...> }
...> }
iex> Litmus.validate(%{"username" => "one_two_three"}, schema)
{:ok, %{"username" => "onetwothree"}}
iex> schema = %{
...> "username" => %Litmus.Type.String{
...> default: "anonymous"
...> }
...> }
iex> Litmus.validate(%{}, schema)
{:ok, %{"username" => "anonymous"}}
Link to this section Summary
Link to this section Types
Specs
t() :: %Litmus.Type.String{ default: any(), length: non_neg_integer() | nil, max_length: non_neg_integer() | nil, min_length: non_neg_integer() | nil, regex: Litmus.Type.String.Regex.t(), replace: Litmus.Type.String.Replace.t(), required: boolean(), trim: boolean() }