Skip to content

Commit

Permalink
URL custom validator
Browse files Browse the repository at this point in the history
  • Loading branch information
ztratify committed Dec 2, 2020
1 parent 93697ca commit a8c7107
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
4 changes: 2 additions & 2 deletions app/models/link.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
class Link < ApplicationRecord
belongs_to :user, optional: true # Prevent ActiveRecord::RecordInvalid

validates :url, presence: true, length: { minimum: 5 }
validates :description, presence: true, length: { minimum: 5 }
validates :url, presence: true, url: true, length: { minimum: 3 }
validates :description, presence: true, length: { minimum: 3 }

has_many :votes
end
12 changes: 12 additions & 0 deletions app/validators/url_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class UrlValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors[attribute] << (options[:message] || "Must be a valid URL") unless url_valid?(value)
end

# a URL may be technically well-formed but may
# not actually be valid, so this checks for both.
def url_valid?(url)
url = URI.parse(url) rescue false
url.kind_of?(URI::HTTP) || url.kind_of?(URI::HTTPS)
end
end

0 comments on commit a8c7107

Please sign in to comment.