Vladimir Sarić wrote this on October 14, 2011
Using jQuery's Validation plugin
Rails validations are a great utility, but sometimes they just don’t fit our needs.
In a recent project, we had a simple signup form on the lander page. The form required an email from the user and nothing else. We, of course, wanted for the email to be a valid one and didn’t want people submitting “you@site.com” as their email, which we used as a hint.
The goal was to do these validations without a page redirect and to alert the user in a way that wouldn’t interfere too much with the lander’s design, meaning we couldn’t use flash messages that we use on other pages. What we needed was a client side validation.
An essential tool in building any professional web application is jQuery. Even though it’s not hard writing client side validations with pure jQuery, that is without any plugins, jQuery’s Validation plugin is just too good to pass on.
The plugin is well documented, but it can be a bit overwhelming. So, I decided to write a quick tutorial on how to use it, and for this purpose I will use the same form and requirements I mentioned above.
First thing we need to do, is to include jQuery and the plugin in our layout:
Now, let’s build the signup form:
Validating that the entered email is present and valid is simple as calling the validate method on our form and adding required: true
and email: true
rules for the user[email]
field:
The great thing about the validate
method is that it sets up event handlers for submit, focus, keyup, blur and click. Meaning, it will trigger the validation on any of those user actions.
We can specify where the error messages will appear on the page by using the errorPlacement
function:
The previous code will append the error messages to the first label on the page, in our case to the “All we need is your email address:” label.
Now, to the fun part, using our own validation rule.
To do this, we first need to define a custom validation method:
The name of the method is email_tip
, which will be used as our rule. Body of the function defines that the value must be different from “you@site.com” and the “Must be different than ‘you@site.com’” part defines the error message that will be used.
Our final validation code looks like this:
Amazing how much you can achieve with just few lines of code. And, of course, you can achieve much much more.