today I create a new project with the phoenix framework, an add an singup function. My problem now is that I don't know how to create and validate a confirmation field, in example for user's password. I didn't find anything to this topic.
Below my current code, nothing special.
My current form template
<%= form_for @changeset, @action, fn f -> %>
<%= if f.errors != [] do %>
<!-- not interesting -->
<% end %>
<div class="form-group">
<%= label f, :username, "User name" %>
<%= text_input f, :username, class: "form-control" %>
</div>
<div class="form-group">
<%= label f, :password, "Password" %>
<%= password_input f, :password, class: "form-control" %>
</div>
<!-- How to validate this??? -->
<div class="form-group">
<%= label f, :password_confirmation, "Password confirmation" %>
<%= password_input f, :password_confirmation, class: "form-control" %>
</div>
<!-- And so on.... -->
<% end %>
My current model
defmodule Project.User do
use Project.Web, :model
schema "users" do
field :username, :string
field :password, :string
timestamps
end
@required_fields ["username", "password"]
@optional_fields []
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
There is a build in validator for this called validate_confirmation/3
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
|> validate_confirmation(:password)
end
The confirmation field can to be added to your scheme as a virtual field too if you want to use it in @required_fields
or @optional_fields
however this is not required to use validate_confirmation
:
schema "users" do
field :username, :string
field :password, :string
field :password_confirmation, :string, virtual: true
timestamps
end
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