Ecto Validate Format is not working for me

Hi guys,

I’m fairly new with Elixir and Ecto. I have been pushing this one all over my plate and I cant seem to see what is going wrong for me. I cant get validate_format to work. I will demonstrate with the Ecto guide (People DB) code.

I create my simple person schema with:

schema "people" do
  field :first_name, :string
  field :last_name, :string
  field :age, :integer

Then I run iex -S mix to be able to play with this simple schema. I create a struct with that schema and then run it through cast, then validate_format:

iex(1)> person = %Friends.Person{first_name: "todd", last_name: "smith", age: 24}
  __meta__: #Ecto.Schema.Metadata<:built, "people">,
  age: 24,
  first_name: "todd",
  id: nil,
  last_name: "smith"

iex(2)> casted = person |> Ecto.Changeset.cast(%{}, [:first_name, :last_name, :age])
#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: #Friends.Person<>,
 valid?: true>

iex(3)> format_test = casted |> Ecto.Changeset.validate_format(:first_name, ~r/steven/)
#Ecto.Changeset<action: nil, changes: %{}, errors: [], data: #Friends.Person<>,
 valid?: true>

According to my understanding, and reading Ecto, validate_format should pull out the value of :first_name which is “todd” and do "todd" =~ ~r/steve/ which should return false, but the changeset is saying its valid data. Im using Ecto 3.6.2 (because this is the version of ecto in the codebase I first encountered this).

Can anyone see what I am doing wrong?

1 Like

Your misunderstanding lies in between the lines. Besides validate_required non of the changeset validations check existing data (person). They only check changes (%{}). Given in your example there are no changes there’s nothing to check.

1 Like

Ok I think I see, so when creating a new Person, I should pass an empty person struct and a map with the new params, which will cause the changes to be registered?


Ok I have it now, thank you very much for your help :slight_smile:


Yes, exactly.

1 Like