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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.