Phoenix Framework - form confirmation field

Today I am creating a new project with a phoenix framework, adding a singup function. My problem is that I do not know how to create and verify a confirmation field, for example, for a user password. I did not find anything in this thread.

Below my current code is 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
+4
source share
1 answer

There is an assembly in the validator for this validate_confirmation / 3

def changeset(model, params \\ :empty) do
  model
  |> cast(params, @required_fields, @optional_fields)
  |> validate_confirmation(:password)
end

A confirmation field can be added to your schema as a virtual field if you want to use it in @required_fieldsor @optional_fields, but 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
+7
source

Source: https://habr.com/ru/post/1599653/


All Articles