Ruby On Rails — Validating Your Password Confirmation On Your Backend

Laurence Hawelu
2 min readMay 14, 2021

I was recently working on a project where I wanted to do the password confirmation validation on the backend instead of doing this on the frontend. After doing some research I was able to locate a validation helper that allowed me to do this. I am going to walk through the process of setting this up on your frontend and backend repositories.

Setting Up The Frontend

For your create user form you will need the standard fields: first name, last name, username, password, and password confirmation. Below is an example of the form using Material-UI:

The main thing to ensure is that password confirmation has a name value of password_confirmation. This is needed in order to ensure that the helper works on the backend.

Setting Up The Backend

Based on the validations docs for Ruby on Rails you will see that there is a helper called confirmation. This validation will look for an attribute that ends with _confirmation. Below is how the docs explain this piece:

This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with “_confirmation” appended.

Let’s go ahead and add the validations to our user model. Below is the code for this:

The first validation will ensure that the value passed in the password attribute matches the password_confirmation attribute. The second validation ensures that password_confirmation is present as well. You will want to adjust your error handling to account for errors so that the end-user knows what is needed.

One additional thing to note, if you are seeding test users you will want to ensure that you include a field for password_confirmation when creating the accounts. Since the validation is verifying that the password_confirmation attribute is present it will be required to create your user seed data.

--

--