How to make Ecto.changeset validate_required accept blank values?
Asked Answered
T

2

7

What I'm trying to do is passing an empty string as the value of a field, and validating it to check if not nil. Problem is that validate_required raise error on both nil and blank values. How to make it accept blank values?

schema

  schema "messages" do
    field :user_id, :string
    field :text, :string

    timestamps()
  end

changeset

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:text, :user_id])
    |> validate_required([:text, :user_id])
  end
Tasha answered 18/8, 2017 at 10:16 Comment(0)
O
14

The behavior of validate_required is unfortunately hardcoded to consider empty as well as whitespace only strings as missing. You can however write a simple function to do the validation:

def changeset(struct, params \\ %{}) do
  struct
  |> cast(params, [:text, :user_id])
  |> validate_not_nil([:text, :user_id])
end

def validate_not_nil(changeset, fields) do
  Enum.reduce(fields, changeset, fn field, changeset ->
    if get_field(changeset, field) == nil do
      add_error(changeset, field, "nil")
    else
      changeset
    end
  end)
end

The function goes over each field, adding error for every field which has a value nil.

Operable answered 18/8, 2017 at 10:24 Comment(1)
This only works if you also declare a default value on the field: field :my_field, :string, default: "" See also the docs on empty values in changesets.Spheroidicity
B
0

https://github.com/elixir-ecto/ecto/issues/1684

Even if that won't fix your problem, adding a default value to the definition will allow you to create a workaround that will completely avoid the null value, even if it is not what you intend.

Beckman answered 9/10, 2022 at 7:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.