How to Integrate Client Side Validations to Check for Uniqueness in Rails

Feature thumb snip20170909 78

Have you ever attempted to register on a site, submitted the form and was told that the username you picked was already taken? Forcing you to re-enter a number of fields, frustrating, right?

In this guide I'm going to walk through how to build an Ajax based validation tool into a Rails application.

Shouldn't there be a Gem for this?

There are a few client side validation gems, such as Judge and client_side_validations. And these can be helpful libraries, but I've found that they don't work great for uniqueness validations, such as the case study I mentioned above.

Rails Client Side Validation for Username Uniqueness

First, I setup a route that the jQuery code can call to see if a username is valid, such as this one:

Then I implement the controller action that looks for a username param to be sent via the Ajax requests and then checks to see if the username is long enough and ensures that it hasn't been taken. Depending on the username, the method will return a JSON response with a key/value pair that will let the jQuery script know if the username is valid or not. Please note, I'm arbitrarily creating that JSON response and key name, you can call it anything that you want.

Now let's create the jQuery script.

There's quite a bit to unpack here, let's take it line by line. I know that I'm going to have page components that show when a username is valid and when it's not. When the script loads I'm hiding them on the page. Next, I'm listening for the keyup event in the username input field. When that event is triggered I make an Ajax call to our new route and controller action. Assuming that the request goes through successfully, I check to see if the username is valid or not, and based on the answer to that question I show and hide the icons on the page. Lastly, I make sure to stop propagation and return false to prevent the Ajax call from happening multiple times.

With all of that in place, I need to add in the icons that will be placed inside of the text field.

Remember that these icons will be hidden when the page loads. In their current location they will sit right next to the label, if you want to place them inside of the text field, you can override the default styles by using absolute values in the CSS, like I did below. Obviously, your styles may need to be different for your own application based on any other styles that could override these.

And that's it! Let's test it out.

If a user enters a username that is too short, it should show that it's invalid:

If a user enters a username that has already been taken, it should show that it's invalid:

And finally, if a user enters a username that's long enough and hasn't been taken, it should show that it's valid.

For additional context, feel free to check out the full repository below: