-
-
Save osulyanov/4942818 to your computer and use it in GitHub Desktop.
Custom model field validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
en: | |
errors: | |
models: | |
model_name: | |
attributes: | |
field_name: | |
reserved: Такое имя пользователя зарезервированно |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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