erlang - How to make Ecto.changeset validate_required accept blank values? -


what i'm trying passing empty string value of field, , validating check if not nil. problem validate_required raise error on both nil , blank values. how make accept blank values?

schema

  schema "messages"     field :user_id, :string     field :text, :string      timestamps()   end 

changeset

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

the behavior of validate_required unfortunately hardcoded consider empty whitespace strings missing. can write simple function validation:

def changeset(struct, params \\ %{})   struct   |> cast(params, [:text, :user_id])   |> validate_not_nil([:text, :user_id]) end  def validate_not_nil(changeset, fields)   enum.reduce(fields, changeset, fn field, changeset ->     if get_field(changeset, field) == nil       add_error(changeset, field, "nil")     else       changeset     end   end) end 

the function goes on each field, adding error every field has value nil.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -