Vex.Validators.Length (Vex v0.9.2) View Source

Ensure a value's length meets a constraint.

Options

At least one of the following must be provided:

  • :min: The value is at least this long
  • :max: The value is at most this long
  • :in: The value's length is within this Range
  • :is: The value's length is exactly this amount.

The length for :is can be provided instead of the options keyword list. The :is is available for readability purposes.

Optional:

  • :tokenizer: A function with arity 1 used to split up a value for length checking. By default binarys are broken up using String.graphemes and all other values (eg, lists) are passed through intact. See Vex.Validators.tokens/1.
  • :message: Optional. A custom error message. May be in EEx format and use the fields described in "Custom Error Messages," below.

Examples

iex> Vex.Validators.Length.validate("foo", 3)
:ok
iex> Vex.Validators.Length.validate("foo", 2)
{:error, "must have a length of 2"}
iex> Vex.Validators.Length.validate(nil, [is: 2, allow_nil: true])
:ok
iex> Vex.Validators.Length.validate("", [is: 2, allow_blank: true])
:ok
iex> Vex.Validators.Length.validate("foo", min: 2, max: 8)
:ok
iex> Vex.Validators.Length.validate("foo", min: 4)
{:error, "must have a length of at least 4"}
iex> Vex.Validators.Length.validate("foo", max: 2)
{:error, "must have a length of no more than 2"}
iex> Vex.Validators.Length.validate("foo", max: 2, message: "must be the right length")
{:error, "must be the right length"}
iex> Vex.Validators.Length.validate("foo", is: 3)
:ok
iex> Vex.Validators.Length.validate("foo", is: 2)
{:error, "must have a length of 2"}
iex> Vex.Validators.Length.validate("foo", in: 1..6)
:ok
iex> Vex.Validators.Length.validate("foo", in: 8..10)
{:error, "must have a length between 8 and 10"}
iex> Vex.Validators.Length.validate("four words are here", max: 4, tokenizer: &String.split/1)
:ok

Custom Error Messages

Custom error messages (in EEx format), provided as :message, can use the following values:

iex> Vex.Validators.Length.__validator__(:message_fields)
[value: "Bad value", tokens: "Tokens from value", size: "Number of tokens", min: "Minimum acceptable value", max: "Maximum acceptable value"]

An example:

iex> Vex.Validators.Length.validate("hello my darling", min: 4, tokenizer: &String.split/1,
...>                                                    message: "<%= length tokens %> words isn't enough")
{:error, "3 words isn't enough"}

Link to this section Summary

Functions

Callback implementation for c:Vex.Validator.Behaviour.validate/2.

Callback implementation for c:Vex.Validator.Behaviour.validate/3.

Link to this section Functions

Link to this function

validate(value, options)

View Source

Callback implementation for c:Vex.Validator.Behaviour.validate/2.

Link to this function

validate(data, context, options)

View Source

Callback implementation for c:Vex.Validator.Behaviour.validate/3.