Ecto: How to fix my custom “Out of range” message?

Hi dear friends
I am new in Elixir
I made a table using Migration
also I create a schema the program is in continue

defmodule Houshold.HtmlApi.Device.DeviceSchema do
  use Ecto.Schema
  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "devices" do        # name of Schema (devises) is equal
    #with name of table that create using Migration
    #defines the structure of data and maps it to a database (like PostgreSQL، MySQL, ...) table.
    field :name, :string 
    timestamps()
  end
  # validate and transform data before saving it to the database
  def changeset(device, params \\ %{}) do
    device
    |> cast(params, [:name]) # Filters and allows only the fields specified in the list
    |> validate_required([:name], message: "fill all fields") #Ensures certain fields are present and cannot be empty
    |> validate_length(:name, max: 10, message: "out of range ") #to validate the length of a field
    end
end

also I made a query

defmodule Houshold.HtmlApi.Device.DeviceQuery do
   alias Houshold.HtmlApi.Device.DeviceSchema, as: DeviceSchema

   # create a function to add device feuture to created teble in Schema
   # atters is a string like: device =  "mobile"

  def add_device(attrs) do
       case Houshold.Repo.insert %DeviceSchema{name: attrs} do
         {:ok, struct}       -> {:ok, struct}
         {:error, changeset} -> {:error, changeset}
       end
   end
end

there is not error but use validation for length of string should not be more than 10 character (validate_length(:name, max: 10, message: "out of range "))
but it didn’t work even when the name is more than 10 character it print the name but I want to print message: "out of range "

thank you

You are not using the changeset but insert directly in the database. Have a look at the link below to learn how changesets should be used; then you will get your error message.

https://hexdocs.pm/ecto/Ecto.Changeset.html

2 Likes