Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rietta
Created October 4, 2012 20:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rietta/3836366 to your computer and use it in GitHub Desktop.
Save rietta/3836366 to your computer and use it in GitHub Desktop.
Rails 3 Bare Domain Validator
#
# Domain Validator by Frank Rietta
# (C) 2012 Rietta Inc. All Rights Reserved.
# Licensed under terms of the BSD License.
#
# To use in a validation, add something like this to your model:
#
# validates :name, :domain => true
#
class DomainValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# The shortest possible domain name something like Google's g.cn, which is four characters long
# The longest possible domain name, as per RFC 1035, RFC 1123, and RFC 2181 is 253 characters
if value.length < 4
record.errors[attribute] << (options[:message] || "is invalid as a bare domain name because it is too short")
elsif value.length > 253
record.errors[attribute] << (options[:message] || "is invalid as a bare domain name because it is too long")
elsif value.include?("://")
record.errors[attribute] << (options[:message] || "is invalid as a bare domain name because it includes a protocol seperator (://)")
elsif value.include?("/")
record.errors[attribute] << (options[:message] || "is invalid as a bare domain name because it includes forward slashes (/)")
elsif !value.include?(".")
record.errors[attribute] << (options[:message] || "is invalid as a bare domain name because it doesn't contain any dots (.)")
else
# Finally, see if the URI parser recognizes this as a valid URL when given a protocol;
# remember, we have already rejected any value that had a protocol specified already
valid = begin
URI.parse("http://" + value).kind_of?(URI::HTTP)
rescue URI::InvalidURIError
false
end
unless valid
record.errors[attribute] << (options[:message] || "is an invalid domain")
end
end
end # validate_each
end # DomainValidator
@eranation
Copy link

Really nice! very useful and well written
p.s.
Hate to be a pedant, but isn't having "is invalid as a bare domain name because it" as a constant a bit more DRY? :)

still great piece of code that I will likely use, thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment