class Person < ApplicationRecord
validates :email, presence: true, email: true
end
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors.add attribute, (options[:message] || "is not an email")
end
end
end
class Model < ActiveRecord
validate :hard_validator_for_name
private
def hard_validator_for_name
if self.name != 'VALID NAME'
errors.add(:name, "name not valid")
end
end
end
2条答案
按热度按时间3okqufwl1#
您可以像这样定义每个属性的自定义验证类:
pu3pd22g2#
您可以使用自定义验证器(https://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations)或使用
validate
方法: