Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate presence in Phoenix framework?

Ecto can validate format, inclusion, uniqueness and so on, but I can't see how I can validate presence? is there a method to add an error to a field if it's empty? Like validates_presence_of in RoR ? I can make it manually, it's not a problem, but I wonder if there is an already existing method for it like validate_presence\3 or something?

like image 910
NoDisplayName Avatar asked Oct 19 '22 04:10

NoDisplayName


1 Answers

Just use the required_fields annotator in the model.

@required_fields ~w(name email)

For a Customer model with a total of 4 fields and 2 required fields like this:

defmodule HelloPhoenix.Customer do
  use HelloPhoenix.Web, :model

  schema "customers" do
    field :name, :string
    field :email, :string
    field :bio, :string
    field :number_of_pets, :integer

    timestamps
  end

  @required_fields ~w(name email)
  @optional_fields ~w()

  def changeset(model, params \\ :empty) do
    model
    |> cast(params, @required_fields, @optional_fields)
  end
end

Phoenix will automatically validate the presence of the required fields and display error messages at the top of the form like below:

enter image description here

like image 178
Lenin Raj Rajasekaran Avatar answered Oct 21 '22 23:10

Lenin Raj Rajasekaran