From fc700a809f78bb6b9545bdbe7072727c3737c7ab Mon Sep 17 00:00:00 2001 From: vishalsodani Date: Sun, 25 Apr 2021 16:40:21 +0530 Subject: [PATCH] added custom error message for validate_numeric and validate_size_of #666 --- spec/validations_spec.cr | 8 ++++++++ src/avram/validations.cr | 12 ++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/spec/validations_spec.cr b/spec/validations_spec.cr index 3ee081d24..aef3e8895 100644 --- a/spec/validations_spec.cr +++ b/spec/validations_spec.cr @@ -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 diff --git a/src/avram/validations.cr b/src/avram/validations.cr index 6147a93b4..f2afbb6ca 100644 --- a/src/avram/validations.cr +++ b/src/avram/validations.cr @@ -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 @@ -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 @@ -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 @@ -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