5

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?

NoDisplayName
  • 15,246
  • 12
  • 62
  • 98

2 Answers2

3

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

Raj
  • 22,346
  • 14
  • 99
  • 142
  • How can I change the custom error message? If I want to show "blah blah" instead of "can't be blank" ... – NoDisplayName Aug 16 '15 at 05:46
  • well, that would be a separate question! – Raj Aug 16 '15 at 05:47
  • well, let's make a separate question then ! There you go -> http://stackoverflow.com/questions/32032246/how-to-add-a-custom-error-message-for-a-required-field – NoDisplayName Aug 16 '15 at 05:48
  • even though it appears to be the way, it doesn't work in my case for some reason, it doesn't add errors to the attributes – NoDisplayName Aug 16 '15 at 06:22
  • @JustMichael check if you are using the latest version of phoenix_ecto package – Raj Aug 16 '15 at 06:27
  • You were right, I was using some old one after all, I've updated it and it broke a few things, so I'll reply when I fix those, thanks for your help – NoDisplayName Aug 16 '15 at 06:27
0

validate_required/3

I can't say how it was in 2015 but for some good time now there's the validate_required/3 function, which serves as an equivalent of "presence" validation in Rails. This function:

Validates that one or more fields are present in the changeset [...]

silverdr
  • 1,978
  • 2
  • 22
  • 27