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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With