Validating email address by defining custom validations in ruby on rails.

This post is more about how to define a custom validation in ruby on rails. I am explaining the same by adding a custom validation for email.

Before:

validates_format_of :email, :with => /A([^@s] )@((?:[-a-z0-9] .)[a-z]{2,})Z/i

Result we want I want to write something like this:

validates :email, :email_format => true

Here is how to do something like this:

Step 1:

Create a new file, i.e., email_format_validator.rb in the lib directory and paste following code there:

class EmailFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless value =~ /^([^@s] )@((?:[-a-z0-9] .)[a-z]{2,})$/i
      object.errors.add(attribute, :email_format, options)
    end
  end
end

Step 2:

Define error message, i.e., Paste this sample code in config/locales/en.yml

# Sample localization file for English. Add more files in this directory for other locales.
# See https://github.com/svenfuchs/rails-i18n/tree/master/rails/locale for starting points.

en:
  hello: "Hello world."
  activerecord:
      errors:
          messages:
              email_format: "is not properly formatted."

Step 3: Auto load validator file, i.e., pastes these two lines in application.rb under config directory.

config.autoload_paths  = %W(#{config.root}/lib)
config.autoload_paths  = Dir["#{config.root}/lib/**/"]

Thats it. Now restart your application. Your custom validator is defined :)