Skip to content

Instantly share code, notes, and snippets.

@danleyb2
Forked from backpackerhh/subdomain_validator.rb
Created December 21, 2018 10:36
Show Gist options
  • Save danleyb2/e1a47248cb7458fe328802b6cfe923eb to your computer and use it in GitHub Desktop.
Save danleyb2/e1a47248cb7458fe328802b6cfe923eb to your computer and use it in GitHub Desktop.
Subdomains validation, inspired by Matthew Hutchinson.
# Each subdivision can go down to 127 levels deep, and each DNS label can contain up to 63 characters,
# as long as the whole domain name does not exceed a total length of 255 characters.
class SubdomainValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
return unless value
reserved_names = %w[admin beta blog ftp imap mail pop pop3 sftp smtp ssl www]
reserved_names += options[:reserved] if options[:reserved]
object.errors[attribute] << 'cannot be a reserved name' if reserved_names.include?(value.downcase)
object.errors[attribute] << 'must have between 3 and 63 characters' unless (3..63) === value.length
object.errors[attribute] << 'cannot start or end with a hyphen' unless value =~ /\A[^-].*[^-]\z/i
object.errors[attribute] << 'must be alphanumeric; A-Z, 0-9 or hyphen' unless value =~ /\A[a-z0-9\-]*\z/i
end
end
require 'spec_helper'
describe SubdomainValidator do
it "valids subdomain" do
foo = Foo.new(subdomain: 'bar')
foo.valid?
expect(foo.errors[:subdomain]).to be_empty
end
it "does not valid subdomain using a reserved name" do
foo = Foo.new(subdomain: 'WWW')
foo.valid?
expect(foo.errors[:subdomain]).to include 'cannot be a reserved name'
end
it "does not valid subdomain length less than 3 characters" do
foo = Foo.new(subdomain: 'ab')
foo.valid?
expect(foo.errors[:subdomain]).to include 'must have between 3 and 63 characters'
end
it "does not valid subdomain length greater than 63 characters" do
foo = Foo.new(subdomain: ('a' * 64))
foo.valid?
expect(foo.errors[:subdomain]).to include 'must have between 3 and 63 characters'
end
it "does not valid hyphen at the beginning of the subdomain" do
foo = Foo.new(subdomain: '-bar')
foo.valid?
expect(foo.errors[:subdomain]).to include 'cannot start or end with a hyphen'
end
it "does not valid hyphen at the end of the subdomain" do
foo = Foo.new(subdomain: 'bar-')
foo.valid?
expect(foo.errors[:subdomain]).to include 'cannot start or end with a hyphen'
end
it "does not valid subdomain with invalid name" do
foo = Foo.new(subdomain: 'bar.beta')
foo.valid?
expect(foo.errors[:subdomain]).to include 'must be alphanumeric; A-Z, 0-9 or hyphen'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment