PhoenixApiToolkit.Ecto.Validators.validate_searchable

You're seeing just the function validate_searchable, go back to PhoenixApiToolkit.Ecto.Validators module for more information.
Link to this function

validate_searchable(changeset, field, search_field, opts \\ [])

View Source

Specs

validate_searchable(Ecto.Changeset.t(), atom(), atom(), keyword()) ::
  Ecto.Changeset.t()

Validate a searchable field. If the value of field is postfixed with '*', a fuzzy search instead of a equal_to match is considered to be intended. In this case, the value must be at least 4 characters long and must be (i)like safe (as per validate_ilike_safe/2), and is moved to search_field. The postfix '*' is stripped from the search string.

The purpose is to pass the changes along to a list-query which supports searching by search_field, and equal_to filtering by field. See PhoenixApiToolkit.Ecto.DynamicFilters for more info on dynamic filtering.

The minimum length for a search string can be overridden with option :min_length.

Examples

For the implementation of changeset/1, see Elixir.PhoenixApiToolkit.Ecto.Validators.

# a last_name value postfixed with '*' is search query
iex> changeset(%{last_name: "Smit*"}) |> validate_searchable(:last_name, :last_name_prefix)
#Ecto.Changeset<action: nil, changes: %{last_name_prefix: "Smit"}, errors: [], data: %{}, valid?: true>

# values without postfix '*' are passed through
iex> changeset(%{last_name: "Smit"}) |> validate_searchable(:last_name, :last_name_prefix)
#Ecto.Changeset<action: nil, changes: %{last_name: "Smit"}, errors: [], data: %{}, valid?: true>

# to prevent too-broad, expensive ilike queries, search parameters must be >=4 characters long
iex> changeset(%{last_name: "Smi*"}) |> validate_searchable(:last_name, :last_name_prefix)
#Ecto.Changeset<action: nil, changes: %{last_name: "Smi"}, errors: [last_name: {"should be at least %{count} character(s)", [count: 4, validation: :length, kind: :min, type: :string]}], data: %{}, valid?: false>

# the min_length value can be overridden
iex> changeset(%{last_name: "Smi*"}) |> validate_searchable(:last_name, :last_name_prefix, min_length: 5)
#Ecto.Changeset<action: nil, changes: %{last_name: "Smi"}, errors: [last_name: {"should be at least %{count} character(s)", [count: 5, validation: :length, kind: :min, type: :string]}], data: %{}, valid?: false>

# additionally, search parameters must be ilike safe, as per validate_ilike_safe/2
iex> changeset(%{last_name: "Sm_it*"}) |> validate_searchable(:last_name, :last_name_prefix)
#Ecto.Changeset<action: nil, changes: %{last_name: "Sm_it"}, errors: [last_name: {"may not contain _ % or \\", [validation: :format]}], data: %{}, valid?: false>