Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phoenix Framework - Confirmation field in form

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
like image 354
Fabi755 Avatar asked Jul 25 '15 15:07

Fabi755


1 Answers

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
like image 112
Gazler Avatar answered Sep 21 '22 11:09

Gazler