From c942cc0e3d704fbaa6c56b2fb12bdf547c883f75 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Fri, 20 Sep 2024 16:41:00 +0700 Subject: [PATCH] Create input_validator.rb --- .../business/lib/input_validator.rb | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 global_business/business/lib/input_validator.rb diff --git a/global_business/business/lib/input_validator.rb b/global_business/business/lib/input_validator.rb new file mode 100644 index 000000000..d08ded9ab --- /dev/null +++ b/global_business/business/lib/input_validator.rb @@ -0,0 +1,24 @@ +class InputValidator + def self.validate(input, rules) + errors = {} + rules.each do |field, rule| + value = input[field] + if value.nil? || value.empty? + errors[field] = "cannot be blank" + elsif rule[:type] == :string + if value.length < rule[:min_length] || value.length > rule[:max_length] + errors[field] = "must be between #{rule[:min_length]} and #{rule[:max_length]} characters" + end + elsif rule[:type] == :email + if !value.match?(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/) + errors[field] = "must be a valid email address" + end + elsif rule[:type] == :password + if value.length < rule[:min_length] + errors[field] = "must be at least #{rule[:min_length]} characters" + end + end + end + errors + end +end