Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added custom error message for validate_numeric and validate_size_of … #670

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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