JQuery validate in Rails applications

JQuery validate in Rails applications

tudip-logo

Tudip

24 June 2016

Let’s quickly look at how can we enable client side validation using Jquery validate in Rails applications. Relying on server-side validation done through the model is fine, but we can improve the usability of the application through client side validation.

JQuery Validation

Jquery Validation is a Jquery plugin for Client side form validation. This Jquery validation plugin makes simple client side form validation with lots of options for customization. This plugin comes bundled with a useful set of validation methods, including URL and email validation while providing APIs to write your own methods. These all methods come with default error messages in
English and translated in 37 locales, though you can override these messages.
Let’s get started.
You can download this plugin from
https://bassistance.de/jquery-plugins/jquery-plugin-validation/
Add this plugin into your application’s assets folder or at place you keep all other JavaScript files.
After the jqury plugin is downloaded include this into your application.js.erb file

//= require jquery.validate

Now you are ready to take benefit of the JQuery validate plugin. For simple form all you have to do is put a validation call like:

$(document).ready(function(){
  $('#new_form').validate();
})

This will validate your form’s fields on submit click event Make sure you have defined your fields in format you want.
Customizing Jquery Validate :
Now we will see how to customize your client side validation as per your needs. There are lots of options provided by JQuery validate plugin. We will see some basic and use some options to customize validations
For further details, you can also refer our other blog entry ‘JQuery Validate Tricks

  • debug If true, the form is not submitted but errors are displayed on the console. It prevents the form from submitting and tries to help setting up the validation with warnings about missing methods and other debug messages. This option is helpful when you are customizing validations. Make sure that you set this option to false after you are done, else your form won’t submit 🙂
$(".new_form").validate({
debug: true
})
  • rules rules are key/value pairs defining custom rules for elements in the form. Where the key is name of the element you are using and value is the rule you want to associate with this field. Please note that in rails, name of an element is created as form[name] instead of name only. If you are creating a form for creating a new user and fields in this form are Email first_name, last_name etc then name of these fields is being created as user[emal], user[first_name],
    user[last_name] resp. While using these name of an elements as key you have to keep in mind to use them in qoutes i.e
    “user[email]” or your jquery will be unable to understand what this name belongs to.
'user[name]': {required : true}

There are lots of rules which you can use like email for email format and so on.

  • remote If you for calling ajax method for checking uniqueness of input written in an element you can use remote. Suppose you want to check uniqueness of your email address or username entered by the new user. Then you are just need to use ‘remote’ rule of JQuery validate. For this you would have to define your rule as
'user[name]': {required : true, remote:'users/check_email'}

Where ‘users/check_email’ is an action defined in users controller. In user_controller.rb, your check_mail method might look like:

def check_email

@user = User.find_by_email(params[:user][:email])

respond_to do |format|

format.json { render :json => !@user }

end

This method will return a JSON with whether user email is already present in the database or not.

  • messages You might need to customize your message to look like what you want
$('.new_user_form').validate({
messages: {
"user[first_name]": "First Name can't be blank",
"user[last_name]": "Last Name can't be blank",
"user[email]": {required: "Email can't be blank", email: "You must
enter a valid email address"},
},
});

You can customize message for every rule you write.

  • errorPlacement This method is very useful when customizing the placement of the error messages. Using this method you can place your messages wherever you want. There are different methods to place your validation message. By default error message shows near element You can show these messages just before/after form element or on the top of the form or at bottom of
    your form. Different methods are –
insertBefore('element_name/class/id'),
insertAfter('element_name/class/id')

An easy way to place these error messages are – append it to perticular Div , span or element you want

$('.new_user_form').validate({
errorPlacement: function(error, element) {
error.appendTo(".errorMessage");
}

In this you can customize the CSS for your messages to look like you want

  • wrapper You can wrap your messages into an outer element by using this option
    $('.new_user_form').validate({
    wrapper: "ul",
    })
    

There are bunch of other options to validate your elements.
onfocusout If true it validate your elemnt on focus out from your element
onkeyup If true it validate your elemnt when you press up key
onclick If true it validate your element onclick on your element
References :

search
Blog Categories
Request a quote