Phoenix - confirmation password field

Greeting! I have a strange issue in password_input field in Phoenix. I want to implement password confirmation, but when I type in the password, then switch to field password_confirmation, the password field clears itself.

            <div>
              <%= label f, :password %>
              <%= password_input f, :password, required: true %>
              <%= error_tag f, :password %>
            </div>

            <div>
              <%= label f, :password_confirmation %>
              <%= password_input f, :password_confirmation, require: true %>
              <%= error_tag f, :password_confirmation %>
            </div>

and then a changeset for this:

def changeset(user, attrs, opts \\ []) do
    user
    |> cast(attrs, [:password])
    |> validate_confirmation(:password, message: "does not match")
    |> validate_password(opts)
  end

1 Like

I’m fairly new to Phoenix, so forgive me if I’m missing something. Here’s what I’ve noticed though:

  • You seem to be using required: true with the first password_input and require: true with the second. So if you’re expecting those to be doing something, it seems at least one of them is wrong.
  • You make a call to validate_password/2. That doesn’t appear to be a pre-defined function for Ecto.Changeset, so if you’ve defined that yourself and the issue is there then you may need to provide the code for that as well.

Also, just a point of clarification, are you saying that the password field is clearing before you submit the form?

1 Like

The markup for the required field should be required.

You may want to include value: input_value(f, :password) and value: input_value(f, :password_confirmation) per the form binding docs.

Then, without seeing the code, I believe you should have your validate_password(opts) before you validate the confirmation.

def changeset(user, attrs, opts \\ []) do  
  user
  |> cast(attrs, [:password])
  |> validate_password(opts)
  |> validate_confirmation(:password, message: "does not match")
end

You don’t need to validate the :password_confirmation if the :password isn’t the correct format you’re looking for. Does that help? :blush:

Edit: should be reply to @floatfoo :heart:

2 Likes

Thanks a lot! Adding value done all the work!

And it is a very helpful notice about validation order! :hugs:

1 Like