-1

Jquery Validation in Rails

I. Introduction:

In Rails, we can validate the state of objects before they go into the database using Active Record's calidatetion feature. This modellevel validations are the best way to ensure that only valid data is saved into your database. But there are several other ways to validate data before saving, include client-side validations. Here an useful tool to validate in view: Jquery Validation.

II. Installation:

Add gem "jquery-validation-rails", including javascript assets and run bundle install

Gemfile

gem "jquery-validation-rails"

app/assets/javascripts/application.js

//= require jquery.validate
//= require jquery.validate.additional-methods

III. Validation:

Here an example of creating a new user using jquery validation

app/views/users/new.html.erb

<%= form_for(@user) do |f| %>
    <%= f.label :username %>
    <%= f.text_field :username %>
    <%= f.label :email %>
    <%= f.text_field :email %>
    <%= f.label :password %>
    <%= f.text_field :password %>
	<%= f.label :password_confirmation %>
    <%= f.text_field :password_confirmation%>
    <%= f.label :birthdate %>
    <%= f.text_field :birthdate %>
    <%= f.label :introduction %>
    <%= f.text_field :introduction %>
<% end %>
<script type="text/javascript">
  <%= render "validate.js" %>
</script>

Adding some simple rules to user form like required, min/maxlength, number, digits...

app/views/users/_validate.js

$("#new_user").validate({
  //error place
  errorPlacement: function (error, element) {
    error.insertBefore(element);
  },
//adding rule
  rules: {
  // username is required with max of 20 and min of 6
  "user[username]":{
    required: true,
    maxlength: 20,
    minlength: 6
  },
  // email is required with format
  "user[email]": {
    required: true,
    email: true
  },
  // password is required
  "user[password]": {
    required: true
  },
  // password_confirmation is required and is the same with password
  "user[password_confirmation]": {
    required: true,
    equalTo: "#user_password"
  },
  // introduction is optional with maxlenght 500
  "user[password_confirmation]": {
    maxlength: 500
  }
  },
  // error messages
  messages: {
    username:{
      required: "Username is required.",
      maxlength: "Username must be less than 20",
      minlength: "Username must be more than 6"
    },
    mail:{
      required: "Email is required",
      email: "Please enter a valid email address"
    },
    password: {
      required: "Password is required"
    },
    password_confirmation: {
      required: "Password confirmation is required",
      equalTo: "Password and password confirmation must be same"
    }
  }
});

We can also adding new rule to our validation by using addMethod method

app/views/users/_validate.js

$("#new_user").validate({
  //error place
  errorPlacement: function (error, element) {
    error.insertBefore(element);
  },
//adding rule
  rules: {
  ...
  // introduction is optional with maxlenght 500
  "user[password_confirmation]": {
    maxlength: 500
  },
  // birthdate is required with format yyyy-mm-dd
  "user[birthdate]": {
    valid_date: 500
  }
  },
  ...
});

$.validator.addMethod("valid_date", function (value, element) {
  return this.optional(element) || isValidDate(value);
}, "Please enter date with form yyyy-mm-dd");

function isValidDate(str) {
  date = new Date(str);
  return !(str != date.toISOString().slice(0, 10));
}

IV. Conclusion:

This Jquery plugin is easy to use but still have plenty of customiztion options. It's a good choice for developing a web's application with Ruby on Rails


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí