Hike News

Custom Validations in rails

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

Validate with custom method

1
2
3
4
5
6
7
8
9
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

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
© 2017 Sandeep Kumar All Rights Reserved.
Theme by hiero