Skip to content

Commit

Permalink
Adding new validation to validate URL formatted attributes. Fixes #667 (
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink authored Sep 28, 2024
1 parent bb63db8 commit 6922463
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
26 changes: 26 additions & 0 deletions spec/avram/validations_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -464,4 +464,30 @@ describe Avram::Validations do
nil_attribute.valid?.should be_true
end
end

describe "validate_url_format" do
it "validates" do
valid_url_attribute = attribute("https://luckyframework.org")
result = Avram::Validations.validate_url_format(valid_url_attribute)
result.should eq(true)
valid_url_attribute.valid?.should be_true

invalid_url_attribute = attribute("http://luckyframework.org")
result = Avram::Validations.validate_url_format(invalid_url_attribute)
result.should eq(false)
invalid_url_attribute.valid?.should be_false
invalid_url_attribute.errors.should eq ["must be a valid URL beginning with https"]

valid_other_attribute = attribute("ftp://user:pass@host:1234/files")
result = Avram::Validations.validate_url_format(valid_other_attribute, scheme: "ftp")
result.should eq(true)
valid_other_attribute.valid?.should be_true

bad_attribute = attribute(" not a URL ")
result = Avram::Validations.validate_url_format(bad_attribute)
result.should eq(false)
bad_attribute.valid?.should be_false
bad_attribute.errors.should eq ["must be a valid URL beginning with https"]
end
end
end
1 change: 1 addition & 0 deletions src/avram/i18n_backend.cr
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ struct Avram::I18n < Avram::I18nBackend
validate_numeric_nil: "must not be nil",
validate_required: "is required",
validate_uniqueness_of: "is already taken",
validate_url_format: "must be a valid URL beginning with %s",
}[key]
end
end
16 changes: 16 additions & 0 deletions src/avram/validations.cr
Original file line number Diff line number Diff line change
Expand Up @@ -330,4 +330,20 @@ module Avram::Validations

true
end

def validate_url_format(
attribute : Avram::Attribute(String),
scheme : String = "https",
message : Avram::Attribute::ErrorMessage = Avram.settings.i18n_backend.get(:validate_url_format)
) : Bool
if url = attribute.value.presence
uri = URI.parse(url)
if uri.scheme != scheme || uri.host.presence.nil?
attribute.add_error(message % scheme)
return false
end
end

true
end
end

0 comments on commit 6922463

Please sign in to comment.