Ecto Custom Field Validation

Minimal snippet to define a custom changeset validation function for a field in Elixir’s Ecto library.

# declare this in your schema file
defp validate_language(changeset, field, options \\ []) do
  validate_change(changeset, field, fn _, str ->
    case str in ["en", "de"] do
      true -> []
      false -> [{field, options[:message] || "Invalid Language"}]

# use it like this
# ...
|> validate_language(:my_field_name)
# ...

This minimal example validates that a given string field contains only allowed values. In this case, language codes are used.

Linked Technologies

What it's made of

illustration of Ecto

A toolkit for data mapping and language integrated query. The Elixir answer to Ruby's ActiveRecord.

illustration of Elixir

Harness the power of concurrent, fault-tolerant programming for scalable, maintainable applications. Code that flows like water!

Linked Categories

Where it's useful

illustration of Data Engineering
Data Engineering

Explore the essentials of Data Engineering, delving into how data systems are built and maintained. From organizing data flows to automating complex data processes, discover the tools and techniques that make data easily accessible and useful for everyday projects and insights.