Validate_required not working as expected

am a bit surprised. in my model i have specified fields that are required in the validate_required function. ironically when i try to submit a form with nil values it submits with no validation errors. This happens only in two models. What could be the reason? Thank you

1 Like

Please show your schemas. ( Remember models are gone in favor of schema since Phoenix 1.3.x :slight_smile: )

In particular, the changeset section, It would be easier to tell…

schema "houses" do
    field :house_type,          :string
    field :house_number,        :string
    field :house_location,      :string



    #Associations
    belongs_to :user, Zito.User, foreign_key: :user_id

    timestamps()
  end


  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:house_type, :house_number, :house_location])
    |> validate_required([:house_type, :house_number, :house_location])
  end

by the way am using Phoenix 1.2

Assuming your app name is Zito and your schema is House…

Try this in the console…

iex> c = Zito.House.changeset %Zito.House{}, %{}

Check that the changeset is invalid.

You should show the code You tried… Like this it’s hard to tell.

BTW Your syntax seems correct so far.

this is what i get

Zito.House.changeset(%Zito.House{__meta__: #Ecto.Schema.Metadata<:built, "houses">,  house_location: nil, house_number: nil, house_type: nil, id: nil, inserted_at: nil, updated_at: nil, user: #Ecto.Association.NotLoaded<association :user is not loaded>, user_id: nil}, %{})

it was just working. never changed, at first i thought maybe i should restart my server. I also did update all my dependancy thought maybe could be an issue with dependancies

If it was working, then broke when You updated… If You kept the old version, I would say restart from it, then update dependencies one by one, to see which break your system.

Sorry, but those errors are hard to debug without more context.

running this in the in the console house = House.changeset(%House{}, %{}) gives me this results

#Ecto.Changeset<
  action: nil,
  changes: %{},
  errors: [
    house_type: {"can't be blank", [validation: :required]},
    house_number: {"can't be blank", [validation: :required]},
    house_location: {"can't be blank", [validation: :required]},
  ],
  data: #Zito.House<>,
  valid?: false
>

The point was to test if the changeset is not valid, as You expect it to be. And it is, so your problem might be in the create action of the house controller.

okay, let me check my create function

Yeah, it had to do with my :create function. I fixed it now validation is working fine.

1 Like