How to validate date string with dry-validation gem?

2.8k Views Asked by At

I want to allow date formatted string with dry-validation gem, but I can't.

class NewUserContract < Dry::Validation::Contract
  params do
    optional(:date).filled(:date)
  end
end
contract = NewUserContract.new

contract.call(date: Date.today)
#=> #<Dry::Validation::Result{:date=>Tue, 14 Jan 2020} errors={}>

# I want to allow date formatted string
contract.call(date: '2020-01-20')
#=> #<Dry::Validation::Result{:date=>"2020-01-20"} errors={:date=>["must be a date"]}>

Date formatted string was allowed until 0.13, but it seems prohibited since 1.0. Now I'm trying to upgrade the dry-validation gem in my Rails app.

EDIT

I am not sure why, but the code above is working now. Maybe caching issue? (I remember I ran bin/rake tmp:cache:clear, though) Please ignore this question.

3

There are 3 best solutions below

0
On BEST ANSWER

I checked with dry-validation 1.4.1, dry-schema 1.4.3 and dry-types 1.2.2 and this works just fine:

require 'dry/validation'

class NewUserContract < Dry::Validation::Contract
  params do
    optional(:date).filled(:date)
  end
end
contract = NewUserContract.new

puts contract.call(date: Date.today).inspect
# #<Dry::Validation::Result{:date=>#<Date: 2020-01-14 ((2458863j,0s,0n),+0s,2299161j)>} errors={}>

puts contract.call(date: '2020-01-20').inspect
# #<Dry::Validation::Result{:date=>#<Date: 2020-01-20 ((2458869j,0s,0n),+0s,2299161j)>} errors={}>
1
On

I have not tested this but I think you can use a Type coercion.

something like:

optional(:date).filled(:date?)



Note: In order to use this, you have to enable some configuration.

configure { config.type_specs = true }
1
On

This code worked in dry-validation 1.4.1!

class NewUserContract < Dry::Validation::Contract
  params do
    optional(:date).filled('params.date')
  end
end
contract = NewUserContract.new

contract.call(date: Date.today)
#=> #<Dry::Validation::Result{:date=>Tue, 14 Jan 2020} errors={}>

contract.call(date: '2020-01-20')
#=> #<Dry::Validation::Result{:date=>Mon, 20 Jan 2020} errors={}>

contract.call(date: 'foo')
#=> #<Dry::Validation::Result{:date=>"foo"} errors={:date=>["must be a date"]}>

'params-date' is defined here: https://github.com/dry-rb/dry-types/blob/v1.2.2/lib/dry/types/params.rb#L11