Skip to content

Instantly share code, notes, and snippets.

@osulyanov
Forked from nbibler/en.yml
Last active December 13, 2015 16:49
Show Gist options
  • Save osulyanov/4942818 to your computer and use it in GitHub Desktop.
Save osulyanov/4942818 to your computer and use it in GitHub Desktop.
Custom model field validation
en:
errors:
models:
model_name:
attributes:
field_name:
reserved: Такое имя пользователя зарезервированно
class FreeAliasValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# TODO: add all routes
routes = %(admin)
if routes.include? value
record.errors.add(attribute, :reserved, options)
elsif User.find_by_name value
record.errors.add(attribute, :reserved, options)
elsif Category.find_by_alias value
record.errors.add(attribute, :reserved, options)
end
end
end
name_regex = /[-a-zA-Z0-9]+$/ui
validates :field,
:presence => true,
:format => {:with => name_regex, :unless => :field_empty?},
:uniqueness => {:case_sensitive => false},
free_alias: true, :on => :create
private
def field_empty?
field.nil? || field.empty?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment