Skip to content

Instantly share code, notes, and snippets.

@rawsyntax
Created January 21, 2011 02:45
Show Gist options
  • Save rawsyntax/789162 to your computer and use it in GitHub Desktop.
Save rawsyntax/789162 to your computer and use it in GitHub Desktop.
an example model (with activemodel validations)
class Example
include ActiveModel::Validations
##
# Validates a URL
#
# If the URI library can parse the value, and the scheme is valid
# then we assume the url is valid
#
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
begin
uri = Addressable::URI.parse(value)
if !["http","https","ftp"].include?(uri.scheme)
raise Addressable::URI::InvalidURIError
end
rescue Addressable::URI::InvalidURIError
record.errors[attribute] << "Invalid URL"
end
end
end
validates :field, :url => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment