### Dry Validation: Conditional Validation Setup Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Initial setup for conditional validation in Dry Validation involves declaring rules for referenced attributes and a custom predicate method. ```ruby key(:payment_type) { |payment_type| payment_type.inclusion?(["card", "cash", "cheque"]) } key(:card_number) { |card_number| card_number.none? | card_number.filled? } ``` ```ruby def paid_with_card?(value) value == "card" end ``` -------------------------------- ### Define Key with Optional Nil Value Source: https://github.com/dry-rb/dry-validation/wiki/Optional-Keys-and-Values This example demonstrates how to define a key `:age` that can either be `nil` or an integer greater than 18, using the `none?` predicate. It includes calls with valid `nil`, valid integer, and invalid integer values. ```ruby require 'dry-validation' class Schema < Dry::Validation::Schema key(:email) { |email| email.filled? } key(:age) do |age| age.none? | (age.int? & age.gt?(18)) end end schema = Schema.new errors = schema.call(email: 'jane@doe.org', age: nil).messages puts errors.inspect # {} errors = schema.call(email: 'jane@doe.org', age: 19).messages puts errors.inspect # {} errors = schema.call(email: 'jane@doe.org', age: 17).messages puts errors.inspect # { :age => [["age must be greater than 18"], 17] } ``` -------------------------------- ### Dry Validation: Complete Conditional Validation Example Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Combines attribute rules, a custom predicate, and a high-level conditional rule to replicate Active Record's `:if` functionality. ```ruby key(:payment_type) { |payment_type| payment_type.inclusion?(["card", "cash", "cheque"]) } key(:card_number) { |card_number| card_number.none? | card_number.filled? } rule(:require_card_number) do rule(:payment_type).paid_with_card? > rule(:card_number). end def paid_with_card?(value) value == "card" end ``` -------------------------------- ### Conditional Absence: Email based on Login Source: https://github.com/dry-rb/dry-validation/wiki/High-level-Rules Ensures an email address is absent when the 'login' field is set to false. This is another example of a rule depending on the specific value of another rule. ```ruby class UserSchema < Dry::Validation::Schema key(:login) { |login| login.bool? } key(:email) { |email| email.none? | email.filled? } rule(:email_absence) do value(:login).false? > rule(:email).none? end end ``` -------------------------------- ### Custom Predicate for Number Check Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation This Ruby predicate checks if a value can be converted to a Float, excluding hexadecimal representations starting with '0x'. It's useful for general number validation when data type is not strictly enforced. ```ruby def value_is_a_number?(value) case value when %r\A0[xX]/ false else begin Kernel.Float(value) rescue ArgumentError, TypeError false end end end ``` -------------------------------- ### Configure Namespace for Schema Source: https://github.com/dry-rb/dry-validation/wiki/Error-Messages Set a default namespace for error messages within a schema. ```ruby class Schema < Dry::Validation::Schema configure { |config| config.namespace = :user } end ``` -------------------------------- ### Define and Use a Basic Validation Schema Source: https://github.com/dry-rb/dry-validation/wiki/Basic Defines a schema to validate email presence and filling, and age as an integer greater than 18. Shows how to call the schema with valid and invalid data and inspect the messages. ```ruby require 'dry-validation' class Schema < Dry::Validation::Schema key(:email) { |email| email.filled? } key(:age) do |age| age.int? & age.gt?(18) end end schema = Schema.new errors = schema.call(email: 'jane@doe.org', age: 19).messages puts errors.inspect # [] errors = schema.call(email: nil, age: 19).messages puts errors.inspect # { :email => [["email must be filled"], nil] } ``` -------------------------------- ### Format Validation (without regex) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Demonstrates how to negate format validation using Dry Validation. ```ruby validates :attr, format: { without: regex } ``` ```ruby key(:attr) { |attr| !attr.format?(regex) } ``` -------------------------------- ### Presence and Format Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Shows how to combine presence and format validation in Dry Validation, mirroring Active Record's approach. ```ruby validates :email, presence: true, format: { with: EMAIL_REGEX } ``` ```ruby key(:email) { |email| email.filled? & email.format?(EMAIL_REGEX) } ``` -------------------------------- ### Configure I18n Messages Source: https://github.com/dry-rb/dry-validation/wiki/Error-Messages Configure a schema to use messages from the I18n gem. Ensure I18n is required and initialized before Dry Validation. ```ruby require 'i18n' require 'dry-validation' class Schema < Dry::Validation::Schema configure { config.messages = :i18n } key(:email, &:filled?) end schema = Schema.new # return default translations puts schema.call(email: '').messages # { :email => ["email must be filled"] } # return other translations (assuming you have it :)) puts schema.call(email: '').messages(locale: :pl) # { :email => ["email musi być wypełniony"] } ``` -------------------------------- ### Confirmation Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Demonstrates the Dry Validation equivalent for Active Record's confirmation validation. ```ruby validates :attr, confirmation: true ``` ```ruby confirmation(:attr) ``` -------------------------------- ### Configure Custom Messages File Source: https://github.com/dry-rb/dry-validation/wiki/Error-Messages Set a custom YAML file for error messages in a schema configuration. ```ruby class Schema < Dry::Validation::Schema configure { |config| config.messages_file = '/path/to/my/errors.yml' } end ``` -------------------------------- ### Format Validation (with regex) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Compares Active Record's format validation with Dry Validation's format? predicate. ```ruby validates :attr, format: { with: regex } ``` ```ruby key(:attr) { |attr| attr.format?(regex) } ``` -------------------------------- ### Shorthand Confirmation Validation Source: https://github.com/dry-rb/dry-validation/wiki/High-level-Rules Provides a concise way to define a password confirmation validation using the 'confirmation' helper. Requires the presence of a corresponding 'password_confirmation' field. ```ruby class Schema < Dry::Validation::Schema confirmation(:password) end ``` -------------------------------- ### Reuse Custom Predicate Container Across Schemas Source: https://github.com/dry-rb/dry-validation/wiki/Custom-Predicates Create a module that includes Dry::Logic::Predicates to define custom predicates. This module can then be configured and reused across multiple schema definitions. ```ruby module MyPredicates include Dry::Logic::Predicates predicate(:email?) do |value| ! /magical-regex-that-matches-emails/.match(value).nil? end end class Schema < Dry::Validation::Schema configure do |config| config.predicates = MyPredicates end key(:email) { |value| value.str? & value.email? } end ``` -------------------------------- ### Define Optional Key with Value Validation Source: https://github.com/dry-rb/dry-validation/wiki/Optional-Keys-and-Values This snippet shows how to define an optional key `:age` that can be `nil` or an integer greater than 18. It demonstrates calling the schema with valid and invalid data to observe error messages. ```ruby require 'dry-validation' class Schema < Dry::Validation::Schema key(:email) { |email| email.filled? } optional(:age) do |age| age.int? & age.gt?(18) end end schema = Schema.new errors = schema.call(email: 'jane@doe.org').messages puts errors.inspect # {} errors = schema.call(email: 'jane@doe.org', age: 17).messages puts errors.inspect # { :age => [["age must be greater than 18"], 17] } ``` -------------------------------- ### Load and Access Custom Messages Source: https://github.com/dry-rb/dry-validation/wiki/Error-Messages Load a custom messages file and access specific error messages based on predicate, rule, and argument types. ```ruby messages = Dry::Validation::Messages.load('/path/to/our/errors.yml') # matching arg type for size? predicate messages[:size?, rule: :name, arg_type: Fixnum] # => "%{name} size must be %{num}" messages[:size?, rule: :name, arg_type: Range] # => "%{name} size must within %{left} - %{right}" # matching val type for size? predicate messages[:size?, rule: :name, val_type: String] # => "%{name} length must be %{num}" # matching predicate messages[:filled?, rule: :age] # => "%{name} must be filled" messages[:filled?, rule: :address] # => "%{name} must be filled" # matching predicate for a specific rule messages[:filled?, rule: :email] # => "the email is missing" # with namespaced messages user_messages = messages.namespaced(:user) user_messages[:filled?, rule: :age] # "% {name} cannot be blank" user_messages[:filled?, rule: :address] # "You gotta tell us where you live" ``` -------------------------------- ### Exclusion Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Shows how to perform exclusion validation using Dry Validation's exclusion? predicate. ```ruby validates :attr, exclusion: { in: array } ``` ```ruby key(:attr){ |attr| attr.exclusion?(array) } ``` -------------------------------- ### Dump Rules to AST Source: https://github.com/dry-rb/dry-validation/wiki/Rule-AST Convert compiled rule objects back into their AST representation using the `to_ary` method. This can be useful for inspecting or serializing the rule structure. ```ruby # dump it back to ast puts rules.map(&:to_ary).inspect ``` ```ruby # [[:and, [:key, [:age, [:predicate, [:key?, [:age]]]]], [[:and, [:val, [:age, [:predicate, [:filled?, []]]]], [[:val, [:age, [:predicate, [:gt?, [18]]]]]]]]] ``` -------------------------------- ### Basic Form Validation Schema Source: https://github.com/dry-rb/dry-validation/wiki/Form-Validation-With-Coercions Defines a form schema with rules for email and age, demonstrating predicate-based validation and type checking. The input hash has stringified keys and values that are strings. ```ruby require 'dry-validation' class UserFormSchema < Dry::Validation::Schema::Form key(:email) { |value| value.str? & value.filled? } key(:age) { |value| value.int? & value.gt?(18) } end schema = UserFormSchema.new errors = schema.call('email' => '', 'age' => '18').messages puts errors.inspect # { # :email => [["email must be filled"], nil], # :age => [["age must be greater than 18"], 18] # } ``` -------------------------------- ### Basic Presence Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Compares Active Record's presence validation with Dry Validation's filled? predicate. ```ruby validates :name, :email, presence: true ``` ```ruby require 'dry-validation' class Schema < Dry::Validation::Schema key(:email) { |email| email.filled? } key(:name) { |name| name.filled? } end ``` ```ruby require 'dry-validation' class Schema < Dry::Validation::Schema key(:email, &:filled?) key(:name, &:filled?) end ``` -------------------------------- ### Confirmation Validation: Password and Password Confirmation Source: https://github.com/dry-rb/dry-validation/wiki/High-level-Rules Validates that the 'password' and 'password_confirmation' fields match. This uses a rule that depends on the values of multiple other rules. ```ruby class Schema < Dry::Validation::Schema key(:password, &:filled?) key(:password_confirmation, &:filled?) rule(:password_confirmation, eql?: [:password, :password_confirmation]) end ``` -------------------------------- ### Conditional Validation with :if in Active Record Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Demonstrates using the `:if` option in Active Record to conditionally apply a validation based on a method's return value. ```ruby validates :card_number, presence: true, if: :paid_with_card? def paid_with_card? payment_type == "card" end ``` -------------------------------- ### Acceptance Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Compares Active Record's acceptance validation with Dry Validation's equality check. ```ruby validates :attr, acceptance: true ``` ```ruby key(:attr){ |attr| attr.eql?('1') } ``` ```ruby validates :attr, acceptance: { accept: 'yes' } ``` ```ruby key(:attr){ |attr| attr.eql?('yes') } ``` -------------------------------- ### Length Validation (Minimum) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Compares Active Record's minimum length validation with Dry Validation's min_size? predicate. ```ruby validates :attr, length: { minimum: int } ``` ```ruby key(:attr) { |attr| attr.min_size?(int) } ``` -------------------------------- ### Generate Rules from AST Source: https://github.com/dry-rb/dry-validation/wiki/Rule-AST Define an AST representing validation rules and use `Dry::Validation::RuleCompiler` to compile them into rule objects. This is useful for programmatically generating complex validation logic. ```ruby ast = [ [ :and, [ [:key, [:age, [:predicate, [:key?, []]]]], [ :and, [ [:val, [:age, [:predicate, [:filled?, []]]]], [:val, [:age, [:predicate, [:gt?, [18]]]]] ] ] ] ] ] compiler = Dry::Validation::RuleCompiler.new(Dry::Validation::Predicates) # compile an array of rule objects rules = compiler.call(ast) puts rules.inspect ``` ```ruby # [ # #> # right=#> # right=#>>> # ] ``` -------------------------------- ### Length Validation (Exact) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Compares Active Record's exact length validation with Dry Validation's size? predicate. ```ruby validates :attr, length: { is: int } ``` ```ruby key(:attr) { |attr| attr.size?(int) } ``` -------------------------------- ### Equal To Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Combines a general number check with an equality comparison, equivalent to Active Record's `validates :attr, numericality: { equal_to: int }`. ```ruby key(:attr){ |attr| attr.value_is_a_number? & attr.eql?(int) } ``` -------------------------------- ### Inclusion Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Shows the Dry Validation equivalent for Active Record's inclusion validation. ```ruby validates :attr, inclusion: { in: array } ``` ```ruby key(:attr) { |attr| attr.inclusion?(array) } ``` -------------------------------- ### Boolean Presence Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Uses the `.bool?` predicate to validate the presence of a boolean field, ensuring it is either true or false. ```ruby key(:attr) { |attr| attr.bool? } ``` -------------------------------- ### Dry Validation Equivalent for :allow_nil Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Use `.none?` within a rule to allow nil values for an attribute, similar to `allow_nil: true` in Active Record. ```ruby key(:attr) { |attr| attr.none? | attr.min_size?(int) } ``` -------------------------------- ### Validate Nested Hash Structure Source: https://github.com/dry-rb/dry-validation/wiki/Nested-Data Define validation rules for nested hash keys using the DSL. Use this when your data contains deeply structured hashes. ```ruby require 'dry-validation' class Schema < Dry::Validation::Schema key(:address) do |address| address.hash? do address.key(:city) do |city| city.min_size?(3) end address.key(:street) do |street| street.filled? end address.key(:country) do |country| country.key(:name, &:filled?) country.key(:code, &:filled?) end end end end schema = Schema.new errors = schema.call({}).messages puts errors.inspect # { :address => ["address is missing"] } errors = schema.call(address: { city: 'NYC' }).messages puts errors.to_h.inspect # { # :address => [ # { :street => [["street is missing"], nil] }, # { :country => [["country is missing"], nil] } # ] # } ``` -------------------------------- ### Conditional Presence: Email based on Login Source: https://github.com/dry-rb/dry-validation/wiki/High-level-Rules Ensures an email address is present only when the 'login' field is set to true. This demonstrates a rule depending on the specific value of another rule. ```ruby class UserSchema < Dry::Validation::Schema key(:login) { |login| login.bool? } key(:email) { |email| email.none? | email.filled? } rule(:email_presence) do value(:login).true? > rule(:email).filled? end end ``` -------------------------------- ### Less Than Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Combines a general number check with a less than comparison, equivalent to Active Record's `validates :attr, numericality: { less_than: int }`. ```ruby key(:attr){ |attr| attr.value_is_a_number? & attr.lt?(int) } ``` -------------------------------- ### Length Validation (Maximum) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Compares Active Record's maximum length validation with Dry Validation's max_size? predicate. ```ruby validates :attr, length: { maximum: int } ``` ```ruby key(:attr) { |attr| attr.max_size?(int) } ``` -------------------------------- ### Basic Numericality Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Uses the custom `value_is_a_number?` predicate to replicate Active Record's basic `validates :name, numericality: true`. ```ruby key(:attr){ |attr| attr.value_is_a_number? } ``` -------------------------------- ### Less Than or Equal To Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Combines a general number check with a less than or equal to comparison, replicating Active Record's `validates :attr, numericality: { less_than_or_equal_to: int }`. ```ruby key(:attr){ |attr| attr.value_is_a_number? & attr.lteq?(int) } ``` -------------------------------- ### Presence Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Uses the `.filled?` predicate to check if an attribute has a value, equivalent to Active Record's `validates :attr, presence: true`. ```ruby key(:attr) { |attr| attr.filled? } ``` -------------------------------- ### Length Validation (Range) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Shows the Dry Validation equivalent for Active Record's length validation within a range. ```ruby validates :attr, length: { in: range } ``` ```ruby key(:attr) { |attr| attr.size?(range) } ``` -------------------------------- ### Dry Validation Equivalent for :allow_blank Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Use `.empty?` within a rule to allow blank values for an attribute, similar to `allow_blank: true` in Active Record. ```ruby key(:attr) { |attr| attr.empty? | attr.min_size?(int) } ``` -------------------------------- ### Define Custom Predicate Method on Schema Source: https://github.com/dry-rb/dry-validation/wiki/Custom-Predicates Define a custom predicate method directly within your schema class. This method can be used in key definitions for validation. ```ruby class Schema < Dry::Validation::Schema key(:email) { |value| value.str? & value.email? } def email?(value) ! /magical-regex-that-matches-emails/.match(value).nil? end end ``` -------------------------------- ### Custom Even Predicate for Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Defines a custom predicate to check if a value is even by converting it to an integer and checking its evenness. ```ruby def even?(value) value.to_i.even end ``` -------------------------------- ### Boolean Absence Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Uses `.exclusion?([true, false])` to validate the absence of a boolean field, ensuring it is neither true nor false. ```ruby key(:attr) { |attr| attr.exclusion?([true, false]) } ``` -------------------------------- ### Absence Validation with Dry Validation (Blank) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Uses the `.blank?` predicate to check if an attribute is absent (e.g., nil, empty string, empty array/hash), replicating Active Record's `validates :attr, absence: true`. ```ruby key(:attr) { |attr| attr.blank? } ``` -------------------------------- ### Absence Validation with Dry Validation (Empty) Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Uses the `.empty?` predicate to check if an attribute is empty (e.g., empty string, empty array/hash), an alternative for Active Record's `validates :attr, absence: true`. ```ruby key(:attr) { |attr| attr.empty? } ``` -------------------------------- ### Custom Odd Predicate for Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Defines a custom predicate to check if a value is odd by converting it to an integer and checking its oddness. ```ruby def odd?(value) value.to_i.odd end ``` -------------------------------- ### Greater Than Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Combines a general number check with a greater than comparison to replicate Active Record's `validates :attr, numericality: { greater_than: int }`. ```ruby key(:attr){ |attr| attr.value_is_a_number? & attr.gt?(int) } ``` -------------------------------- ### Dry Validation: Implementing Conditional Rule Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation A high-level rule is declared to enforce the presence of `card_number` only when `payment_type` is 'card', using the custom predicate. ```ruby rule(:require_card_number) do rule(:payment_type).paid_with_card? > rule(:card_number).filled? end ``` -------------------------------- ### Greater Than or Equal To Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Combines a general number check with a greater than or equal to comparison, mirroring Active Record's `validates :attr, numericality: { greater_than_or_equal_to: int }`. ```ruby key(:attr){ |attr| attr.value_is_a_number? & attr.gteq?(int) } ``` -------------------------------- ### Validate Nested Array Elements Source: https://github.com/dry-rb/dry-validation/wiki/Nested-Data Use the 'each' rule to validate every element within a nested array. This is useful for lists of items like phone numbers or emails. ```ruby class Schema < Dry::Validation::Schema key(:phone_numbers) do |phone_numbers| phone_numbers.array? do phone_numbers.each(&:str?) end end end schema = Schema.new errors = schema.call(phone_numbers: '').messages puts errors.inspect # { :phone_numbers => [["phone_numbers must be an array"], ""] errors = schema.call(phone_numbers: ['123456789', 123456789]).messages puts errors.inspect # { # :phone_numbers => [ # [{ :phone_numbers => [["phone_numbers must be a string"], 123456789] }], # ["123456789", 123456789] # ] # } ``` -------------------------------- ### Conditional Rule: Barcode Only Source: https://github.com/dry-rb/dry-validation/wiki/High-level-Rules Defines a high-level rule that ensures if a barcode is provided, then job and sample numbers must be absent. This builds upon individual key validations. ```ruby class BarcodeSchema < Dry::Validation::Schema key(:barcode) do |barcode| barcode.none? | barcode.filled? end key(:job_number) do |job_number| job_number.none? | job_number.int? end key(:sample_number) do |sample_number| sample_number.none? | sample_number.int? end rule(:barcode_only) do rule(:barcode).filled? & (rule(:job_number).none? & rule(:sample_number).none?) end end ``` -------------------------------- ### Integer Validation with Dry Validation Source: https://github.com/dry-rb/dry-validation/wiki/Active-Record-Validation-Equivalents-in-Dry-Validation Replicates Active Record's `validates :attr, numericality: { only_integer: true }` by using a regular expression to ensure the attribute contains only digits, optionally preceded by a sign. ```ruby key(:attr){ |attr| attr.format?(/\[A-Z+-]?\d+\Z/) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.