How to check availability in Phoenix infrastructure?

Ecto can check format, inclusion, uniqueness, etc., but I don’t see how I can check presence? is there any way to add an error to the field if it is empty? How to validates_presence_of in RoR? I can do it manually, this is not a problem, but I wonder if there is already an existing method for it like validate_presence\3 or something else?

+5
source share
1 answer

Just use the required_fields annotator in the model.

 @required_fields ~w(name email) 

For the Customer model, containing a total of 4 fields and 2 required fields:

 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 confirm the required fields and display error messages at the top of the form, as shown below:

enter image description here

+3
source

All Articles