Skip to content

Instantly share code, notes, and snippets.

@chebyte
Last active December 17, 2015 03:09
Show Gist options
  • Save chebyte/5540928 to your computer and use it in GitHub Desktop.
Save chebyte/5540928 to your computer and use it in GitHub Desktop.
custom social url validator for rails
#lib/validators/social_url_validator.rb
class SocialUrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
value = smart_add_scheme_url_to record, attribute, value
case attribute
when :facebook
record.errors.add attribute, (options[:message] || "not a valid domain") unless
value =~ /((http|https):\/\/)?(www[.])?facebook.com\/.+/i
when :twitter
record.errors.add attribute, (options[:message] || "not a valid domain") unless
value =~ /((http|https):\/\/)?(www[.])?twitter.com\/.+/i
when :linkedin
record.errors.add attribute, (options[:message] || "not a valid domain") unless
value =~ /((http|https):\/\/)?(www[.])?linkedin.com\/.+/i
when :xing
record.errors.add attribute, (options[:message] || "not a valid domain") unless
value =~ /((http|https):\/\/)?(www[.])?xing.com\/profile\/.+/i
end
end
def smart_add_scheme_url_to record, attribute, value
url = value
unless value[/^(http|https):\/\//]
url = 'http://' << value
record.send("#{attribute}=", url)
end
url
end
end
#config/application.rb
config.autoload_paths += %W(#{config.root}/lib #{config.root}/lib/validators)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment