Codementor Events

Custom Validations in Rails

Published Feb 02, 2018

Validation is one of the core features which rails provides. There are plenty of built in validation helpers there which helps validating our form inputs or user attributes. But in few cases, if these built in validation helper doesn’t serve your purpose, rails provide support for writing your own custom validators as well. There are many ways to write custom validations. Few of them are:

Validate with custom method

class Post < ApplicationRecord
  validate :custom_validation
  private def custom_validation
    if ! (valid...)
      self.errors[:base] << "Custom error message"
    end
  end
end

Validate with ActiveModel validation

class CustomValidator < ActiveModel::Validator
  def validate(record)
    if ! (record.valid...)
      record.errors[:base] << "Custom Error message"
    end
  end
end
class Post < ApplicationRecord
  validates_with CustomValidator
end

Validate with PORO class

class PoroValidator
  def initialize(record)
    @record = record
  end
  def call
    if ! (@record.valid...)
      @record.errors[:base] << "Custom Error Messages"
    end
  end
end
class Post < ApplicationRecord
  validate do |record|
    PoroValidator.new(record).()
  end
end
Discover and read more posts from sandeep kumar
get started