Managing Registration Changesets

You’ve already seen a changeset for creating a new user—the one that handles the name and username. Let’s review that now:

 def​ changeset(model, params \\ ​:empty​) ​do
  model
  |> cast(params, ​~​w(name username), [])
  |> validate_length(​:username​, ​min:​ 1, ​max:​ 20)
 end

The Ecto.Changeset.cast function converts that naked map to a changeset and, for security purposes, limits the inbound parameters to the ones you specify. Then, we fire a validation limiting the length of valid usernames to one to twenty characters. Remember, we need to supply :empty parameters instead of an empty map so Ecto can distinguish our blank new changeset from an empty form submission ...

Get Programming Phoenix now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.