Last active
October 25, 2021 22:33
-
-
Save stuartbain/7212385 to your computer and use it in GitHub Desktop.
Custom validator for Subdomains
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 SubdomainValidator < ActiveModel::EachValidator | |
# http://matthewhutchinson.net/2010/10/27/rails-3-subdomain-validation-activemodeleachvalidator | |
def validate_each(object, attribute, value) | |
return unless value.present? | |
reserved_names = %w(www ftp mail pop smtp admin ssl sftp) | |
reserved_names = options[:reserved] if options[:reserved] | |
if reserved_names.include?(value) | |
object.errors[attribute] << 'cannot be a reserved name' | |
end | |
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 (or hyphen)' unless value =~ /\A[a-z0-9\-]*\z/i | |
end | |
end |
Thanks ❤️
I created a javascript version of this with a small tweak.
https://gist.github.com/mohammadwali/af11bb30b7a687a8908c9496c49f4faa
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks.
Here are the tests for it written in RSpec: