Skip to content

Commit

Permalink
added custom error message for validate_numeric and validate_size_of #…
Browse files Browse the repository at this point in the history
  • Loading branch information
vishalsodani committed Apr 29, 2021
1 parent 625aa38 commit fc700a8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
8 changes: 8 additions & 0 deletions spec/validations_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,14 @@ describe Avram::Validations do

second.errors.should eq(["not even close"])
end

it "validates custom message for validate_numeric" do
too_small_attribute = attribute(1)

Avram::Validations.validate_numeric too_small_attribute, greater_than: 2, message: "number is too small"

too_small_attribute.errors.should eq(["number is too small"])
end
end

describe "validate_acceptance_of" do
Expand Down
12 changes: 8 additions & 4 deletions src/avram/validations.cr
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,12 @@ module Avram::Validations
# validate_size_of feedback, min: 18, max: 100
# validate_size_of password, min: 12
# ```
# ameba:disable Metrics/CyclomaticComplexity
def validate_size_of(
attribute : Avram::Attribute(String),
min = nil,
max = nil,
message = nil,
allow_nil : Bool = false
)
if !min.nil? && !max.nil? && min > max
Expand All @@ -143,11 +145,11 @@ module Avram::Validations
size = attribute.value.to_s.size

if !min.nil? && size < min
attribute.add_error "is too short"
attribute.add_error message || "is too short"
end

if !max.nil? && size > max
attribute.add_error "is too long"
attribute.add_error message || "is too long"
end
end
end
Expand All @@ -158,10 +160,12 @@ module Avram::Validations
# validate_numeric age, greater_than: 18
# validate_numeric count, greater_than: 0, less_than: 1200
# ```
# ameba:disable Metrics/CyclomaticComplexity
def validate_numeric(
attribute : Avram::Attribute(Number),
greater_than = nil,
less_than = nil,
message = nil,
allow_nil : Bool = false
)
if greater_than && less_than && greater_than > less_than
Expand All @@ -178,11 +182,11 @@ module Avram::Validations
end

if greater_than && number < greater_than
attribute.add_error "is too small"
attribute.add_error message || "is too small"
end

if less_than && number > less_than
attribute.add_error "is too large"
attribute.add_error message || "is too large"
end
end
end

0 comments on commit fc700a8

Please sign in to comment.