Giter VIP home page Giter VIP logo

validates_timeliness's Introduction

ValidatesTimeliness build

Description

Complete validation of dates, times and datetimes for Rails 7.x and ActiveModel.

Older Rails versions:

Features

  • Adds validation for dates, times and datetimes to ActiveModel
  • Handles timezones and type casting of values for you
  • Only Rails date/time validation plugin offering complete validation (See ORM/ODM support)
  • Uses extensible date/time parser (Using timeliness gem. See Plugin Parser)
  • Adds extensions to fix Rails date/time select issues (See Extensions)
  • Supports I18n for the error messages. For multi-language support try timeliness-i18n gem.
  • Supports all the Rubies (that any sane person would be using in production).

Installation

In Gemfile

gem 'validates_timeliness', '~> 7.0.0.beta1'

Run bundler:

$ bundle install

Then run

$ rails generate validates_timeliness:install

This creates configuration initializer and locale files. In the initializer, there are a number of config options to customize the plugin.

NOTE: You may wish to enable the plugin parser and the extensions to start. Please read those sections first.

Examples

validates_datetime :occurred_at

validates_date :date_of_birth, before: lambda { 18.years.ago },
                                before_message: "must be at least 18 years old"

validates_datetime :finish_time, after: :start_time # Method symbol

validates_date :booked_at, on: :create, on_or_after: :today # See Restriction Shorthand.

validates_time :booked_at, between: ['9:00am', '5:00pm'] # On or after 9:00AM and on or before 5:00PM
validates_time :booked_at, between: '9:00am'..'5:00pm' # The same as previous example
validates_time :booked_at, between: '9:00am'...'5:00pm' # On or after 9:00AM and strictly before 5:00PM

validates_time :breakfast_time, on_or_after: '6:00am',
                                on_or_after_message: 'must be after opening time',
                                before: :lunchtime,
                                before_message: 'must be before lunch time'

Usage

To validate a model with a date, time or datetime attribute you just use the validation method:

class Person < ActiveRecord::Base
  validates_date :date_of_birth, on_or_before: lambda { Date.current }
  # or
  validates :date_of_birth, timeliness: { on_or_before: lambda { Date.current }, type: :date }
end

or even on a specific record, per ActiveModel API.

@person.validates_date :date_of_birth, on_or_before: lambda { Date.current }

The list of validation methods available are as follows:

  • validates_date - validate value as date
  • validates_time - validate value as time only i.e. '12:20pm'
  • validates_datetime - validate value as a full date and time
  • validates - use the :timeliness key and set the type in the hash.

The validation methods take the usual options plus some specific ones to restrict the valid range of dates or times allowed

Temporal options (or restrictions):

  • :is_at - Attribute must be equal to value to be valid
  • :before - Attribute must be before this value to be valid
  • :on_or_before - Attribute must be equal to or before this value to be valid
  • :after - Attribute must be after this value to be valid
  • :on_or_after - Attribute must be equal to or after this value to be valid
  • :between - Attribute must be between the values to be valid. Range or Array of 2 values.

Regular validation options:

  • :allow_nil - Allow a nil value to be valid
  • :allow_blank - Allows a nil or empty string value to be valid
  • :if - Execute validation when :if evaluates true
  • :unless - Execute validation when :unless evaluates false
  • :on - Specify validation context e.g :save, :create or :update. Default is :save.

Special options:

  • :ignore_usec - Ignores microsecond value on datetime restrictions
  • :format - Limit validation to a single format for special cases. Requires plugin parser.

The temporal restrictions can take 4 different value types:

  • Date, Time, or DateTime object value
  • Proc or lambda object which may take an optional parameter, being the record object
  • A symbol matching a method name in the model
  • String value

When an attribute value is compared to temporal restrictions, they are compared as the same type as the validation method type. So using validates_date means all values are compared as dates.

Configuration

ORM/ODM Support

The plugin adds date/time validation to ActiveModel for any ORM/ODM that supports the ActiveModel validations component. However, there is an issue with most ORM/ODMs which does not allow 100% date/time validation by default. Specifically, when you assign an invalid date/time value to an attribute, most ORM/ODMs will only store a nil value for the attribute. This causes an issue for date/time validation, since we need to know that a value was assigned but was invalid. To fix this, we need to cache the original invalid value to know that the attribute is not just nil.

Each ORM/ODM requires a specific shim to fix it. The plugin includes a shim for ActiveRecord and Mongoid. You can activate them like so

ValidatesTimeliness.setup do |config|
  # Extend ORM/ODMs for full support (:active_record).
  config.extend_orms = [ :active_record ]
end

By default the plugin extends ActiveRecord if loaded. If you wish to extend another ORM then look at the wiki page for more information.

It is not required that you use a shim, but you will not catch errors when the attribute value is invalid and evaluated to nil.

Error Messages

Using the I18n system to define new defaults:

en:
  errors:
    messages:
      invalid_date: "is not a valid date"
      invalid_time: "is not a valid time"
      invalid_datetime: "is not a valid datetime"
      is_at: "must be at %{restriction}"
      before: "must be before %{restriction}"
      on_or_before: "must be on or before %{restriction}"
      after: "must be after %{restriction}"
      on_or_after: "must be on or after %{restriction}"

The %{restriction} signifies where the interpolation value for the restriction will be inserted.

You can also use validation options for custom error messages. The following option keys are available:

:invalid_date_message
:invalid_time_message
:invalid_datetime_message
:is_at_message
:before_message
:on_or_before_message
:after_message
:on_or_after_message

Note: There is no :between_message option. The between error message should be defined using the :on_or_after and :on_or_before (:before in case when :between argument is a Range with excluded high value, see Examples) messages.

It is highly recommended you use the I18n system for error messages.

Plugin Parser

The plugin uses the timeliness gem as a fast, configurable and extensible date and time parser. You can add or remove valid formats for dates, times, and datetimes. It is also more strict than the Ruby parser, which means it won't accept day of the month if it's not a valid number for the month.

By default the parser is disabled. To enable it:

# in the setup block
config.use_plugin_parser = true

Enabling the parser will mean that strings assigned to attributes validated with the plugin will be parsed using the gem. See the wiki for more details about the parser configuration.

Restriction Shorthand

It is common to restrict an attribute to being on or before the current time or current day. To specify this you need to use a lambda as an option value e.g. lambda { Time.current }. This can be tedious noise amongst your validations for something so common. To combat this the plugin allows you to use shorthand symbols for often used relative times or dates.

Just provide the symbol as the option value like so:

validates_date :birth_date, on_or_before: :today

The :today symbol is evaluated as lambda { Date.current }. The :now and :today symbols are pre-configured. Configure your own like so:

# in the setup block
config.restriction_shorthand_symbols.update(yesterday: lambda { 1.day.ago })

Default Timezone

The plugin needs to know the default timezone you are using when parsing or type casting values. If you are using ActiveRecord then the default is automatically set to the same default zone as ActiveRecord. If you are using another ORM you may need to change this setting.

# in the setup block
config.default_timezone = :utc

By default it will be UTC if ActiveRecord is not loaded.

Dummy Date For Time Types

Given that Ruby has no support for a time-only type, all time type columns are evaluated as a regular Time class objects with a dummy date value set. Rails defines the dummy date as 2000-01-01. So a time of '12:30' is evaluated as a Time value of '2000-01-01 12:30'. If you need to customize this for some reason you can do so as follows:

# in the setup block
config.dummy_date_for_time_type = [2009, 1, 1]

The value should be an array of 3 values being year, month and day in that order.

Temporal Restriction Errors

When using the validation temporal restrictions there are times when the restriction option value itself may be invalid. This will add an error to the model such as 'Error occurred validating birth_date for :before restriction'. These can be annoying in development or production as you most likely just want to skip the option if no valid value was returned. By default these errors are displayed in Rails test mode.

To turn them on/off:

# in the setup block
config.ignore_restriction_errors = true

Extensions

Strict Parsing for Select Helpers

When using date/time select helpers, the component values are handled by ActiveRecord using the Time class to instantiate them into a time value. This means that some invalid dates, such as 31st June, are shifted forward and treated as valid. To handle these cases in a strict way, you can enable the plugin extension to treat them as invalid dates.

To activate it, uncomment this line in the initializer:

# in the setup block
config.enable_multiparameter_extension!

Display Invalid Values in Select Helpers

The plugin offers an extension for ActionView to allowing invalid date and time values to be redisplayed to the user as feedback, instead of a blank field which happens by default in Rails. Though the date helpers make this a pretty rare occurrence, given the select dropdowns for each date/time component, but it may be something of interest.

To activate it, uncomment this line in the initializer:

# in the setup block
config.enable_date_time_select_extension!

Contributors

To see the generous people who have contributed code, take a look at the contributors list.

Maintainers

License

Copyright (c) 2021 Adam Meehan, released under the MIT license.

validates_timeliness's People

Contributors

aditya-kapoor avatar adzap avatar alebl avatar anandbait avatar carlosantoniodasilva avatar cgriego avatar cyclotron3k avatar dependabot[bot] avatar guillaumebriday avatar jarl-dk avatar johnnyshields avatar josevalim avatar kamillle avatar monkbroc avatar obfuscoder avatar pedrofurtado avatar reiz avatar rudyonrails avatar schinery avatar tagliala avatar tastypi avatar timdiggins avatar vsppedro avatar xmartin avatar yxf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

validates_timeliness's Issues

If blank values are allowed, then no errors are given on invalid formats

Hi Adam

If I allow blank values on a date field, and an invalid date is entered, then nil is stored an no error given. I dont think it was like this in the past.

Example:

validates(:contract_expires, :timeliness => {:type => :date, :allow_blank => true})

I use Ruby 1.9.2, Rails 3.1.1 and validates_timliness 3.0.7

allow_blank doesn't work with validates_date

Hello,

I have a MySQL date column and the following validation :

validates_date :date, :allow_blank => true, :on_or_before => :today

if date is blank, plugin add error "is not a valid date" on the field.

All is ok with :

validates :date, :timeliness => { :allow_blank => true, :on_or_before => :today, :type => :date}

Thanks for your help,

Raphaรซl

Validates Timeliness triggers an error in a class where it's not used..

Hello,

I've installed yesterday this gem (v.2.3.2) in v2.3.2 Rails application. I've realised this morning that it triggers unexpected errors in another class, where i do not use date validations.

The following line triggers a TypeError (can't convert Range into Integer).

Any ideas on how to fix this?

current_wt.online = 1.seconds

The top of the call stack is:

vendor/rails/activesupport/lib/active_support/duration.rb:95:in []' vendor/rails/activesupport/lib/active_support/duration.rb:95:insend'
vendor/rails/activesupport/lib/active_support/duration.rb:95:in method_missing' /var/lib/gems/1.8/gems/validates_timeliness-2.3.2/lib/validates_timeliness/parser.rb:16:inparse'
/var/lib/gems/1.8/gems/validates_timeliness-2.3.2/lib/validates_timeliness/active_record/attribute_methods.rb:27:in write_date_time_attribute' /var/lib/gems/1.8/gems/validates_timeliness-2.3.2/lib/validates_timeliness/active_record/attribute_methods.rb:56:inonline='
app/models/worktime.rb:17:in new_hit' app/controllers/application_controller.rb:120:inupdate_hit_time'

Validate_timeliness breaks ability to override setters for date fields

Thanks for this excellent plugin.
However, I think i found a major issue.

class Foo < ActiveRecord::Base
#table includes field date field called bar

def bar=(value)
do_something
write_attribute(:bar, value)
end
end

The method above does not get invoked when Validate_timeliness is installed with rails 2.1
This usage is allowed per http://api.rubyonrails.org/classes/ActiveRecord/Base.html, section "Overwriting default accessors"

Datetime attribute set to nil in the record when invalid.

o schema.rb:

create_table "roles", :force => true do |t|
t.integer "worker_id"
t.integer "structure_id"
t.string "structure_type"
t.datetime "started_on"
t.datetime "ended_on"
...

o Model (role.rb):

class Role < ActiveRecord::Base
validates_datetime :started_on, :allow_blank => true
validates_datetime :ended_on, :allow_blank => true
...

o When trying to update started_on with a stupid value in console (can't format properly, sorry):

role = Role.find(4)
ManagerRole id: 4, worker_id: 44, structure_id: 7, type: "ManagerRole", started_on: "2009-07-20 00:00:00", ended_on: nil ...

role.started_on='foo'
foo

role.started_on
nil

Why nil instead of the initial value ?

Cheers. Stan.

Bad type after validation with validates_date but ok using validates with type

Hello,

I have a MySQL date column and the following validation :

validates_date :date, :allow_blank => true, :on_or_before => :today

if date isn't valid (after today for example) the following code :

f.text_field(:date, :value => f.object.date, :class => "date")

give me the following output :

26/03/2011 00:00

which isn't the format of a date field (formated like a datetime field). If I remove the validation (and fail on another field) the output is :

26/03/2011

which is OK for date field.

All is ok with :

validates :date, :timeliness => { :allow_blank => true, :on_or_before => :today, :type => :date}

Thanks for your help,

Raphaรซl

undefined method `validates_date' after installation

In a Rails 3.1.1 project I've installed validates_timeliness as a gem, and ran the installation command.

This is in my Gemfile: gem 'validates_timeliness', '~> 3.0.8'

However, if I now include validates_date in my model, I get

ActionController::RoutingError (undefined method validates_date' for #<Class:0x0000001fb6ec88>): app/models/user.rb:8:inclass:User'
app/models/user.rb:1:in <top (required)>' app/controllers/users_controller.rb:3:in<top (required)>'

If I run rails console, I can perform timeliness methods such as Timeliness.parse('2010-09-08 12:13:14') and Timeliness.parse('2010-09-08 12:13:14', :zone => :local). And if I add garbage to validates_timeliness.rb, the console won't start. My application? Doesn't care.

So somehow validates_timeliness isn't autoloading, but I don't know where to look.

An invalid date give empty: "..." error message Rails 3

Hi,

My config:

validates_timeliness.rb:
config.parser.remove_us_formats

environment.rb:
Date::DATE_FORMATS[:default] = "%d.%m.%Y"

Model:
validates :date_naissance, :timeliness => {:on_or_before => lambda { 14.years.ago }, :type => :date, :on_or_before_message => "To young" }

When I set an invalid date in my view (ie. 32.12.2000) the error message is empty: "..."
The field in the view is still there.
on_or_before validation works fine with a valid date.

How can I manage that to display the correct message => invalid_date: "is not a valid date"

MultiparameterAssignmentErrors

Hi,

I'm getting a MultiparameterAssignmentError when enabling the multiparameter extension:

u = User.new(:name => 'foo', "dob(1i)"=>"1902", "dob(2i)"=>"2", "dob(3i)"=>"31")
ActiveRecord::MultiparameterAssignmentErrors: 1 error(s) on assignment of multiparameter attributes
    from /Users/trusche/.rvm/gems/ruby-1.8.7-p302@rails3/gems/activerecord-3.0.2/lib/active_record/base.rb:1787:in `execute_callstack_for_multiparameter_attributes'
    from /Users/trusche/.rvm/gems/ruby-1.8.7-p302@rails3/gems/activerecord-3.0.2/lib/active_record/base.rb:1742:in `assign_multiparameter_attributes'
    from /Users/trusche/.rvm/gems/ruby-1.8.7-p302@rails3/gems/activerecord-3.0.2/lib/active_record/base.rb:1563:in `attributes='
    from /Users/trusche/.rvm/gems/ruby-1.8.7-p302@rails3/gems/activerecord-3.0.2/lib/active_record/base.rb:1406:in `initialize'
    from (irb):1:in `new'

I've set up a clean rails 3 up to rule out any other gems or plugins interfering. Note that I'm getting this on assignment - before even validating. Here's my config:

ValidatesTimeliness.setup do |config|
  # Extend ORM/ODMs for full support (:active_record, :mongoid).
  config.extend_orms = [ :active_record ]
  #
  # Default timezone
  # config.default_timezone = :utc
  #
  # Set the dummy date part for a time type values.
  # config.dummy_date_for_time_type = [ 2000, 1, 1 ]
  #
  # Ignore errors when restriction options are evaluated
  config.ignore_restriction_errors = false
  #
  # Re-display invalid values in date/time selects
  config.enable_date_time_select_extension!
  #
  # Handle multiparameter date/time values strictly
  config.enable_multiparameter_extension!
  #
  # Shorthand date and time symbols for restrictions
  # config.restriction_shorthand_symbols.update(
  #   :now   => lambda { Time.current },
  #   :today => lambda { Date.current }
  # )
  #
  # Use the plugin date/time parser which is stricter and extendable
  # config.use_plugin_parser = false
  #
  # Add one or more formats making them valid. e.g. add_formats(:date, 'd(st|rd|th) of mmm, yyyy')
  # config.parser.add_formats()
  #
  # Remove one or more formats making them invalid. e.g. remove_formats(:date, 'dd/mm/yyy')
  # config.parser.remove_formats()
  #
  # Change the amiguous year threshold when parsing a 2 digit year
  # config.parser.ambiguous_year_threshold =  30
  #
  # Treat ambiguous dates, such as 01/02/1950, as a Non-US date.
  # config.parser.remove_us_formats
end

When I comment out the "config.enable_multiparameter_extension!" line it doesn't throw the Exception (but doesn't prevent date rollover either, which is what I want to achieve).

Any ideas? This happens on rails 3.0.1 and 3.0.2, plugin version 3.0.1

Thanks!

validates_date seems to break form helper

If in my model I have something like

class Person
validates_date :birthday
end

And in view code something like

<%= form_for @person do |f| %>
<%= f.text_field :birthday %>:
<% end %>

The text field is not autopopulated with the existing value for :birthday. However, the following does work:

<%= form_for @person do |f| %>
<%= text_field_tag 'person[birthday]', @person.birthday %>:
<% end %>

2 year dates

Hi,

Thanks for this great gem.

I have a little problem using it, but it could be implementation error. Basically, when people enter a 2 digit year, for example 1/1/86, it keeps gets saved as 0086-1-1. I can't seem to get the century in there. I have played with the initializer file, and uncommented this line:
config.parser.ambiguous_year_threshold = 30

but nothing.

Am I missing something?

I'm using ruby 1.8.7 and rails 3.0.7.

Thank you!

Unable to get Unit Test Validation Message and Server Message to Agree

I am on Rails 2.3.4 and validates_timeliness 2.3.2

In my model I have this:

validates_date :publish_on, :on_or_after => Date.today()

I validate it with a unit test, using this passing assertion:

assert_equal ["Publish on must be on or after #{Date.today}"], @min_offer.errors.full_messages

However, when I run up the app in the server, the validation will fail when expected but returns this message:

 Publish on is not a valid date

I do not use the form helper to get the messages I use this:

 <% offer.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>

What do I need to do or configure so that I get the nicer, more complete message in the Unit test to show up on the page when I run the app?

Thanks.

MultiparameterAssignmentErrors

This issue is exactly the same as #27.

1.9.3p0 :002 > p = Profile.new("birthday(3i)" => "2000", "birthday(2i)" => "2", "birthday(1i)" => "31")
ActiveRecord::MultiparameterAssignmentErrors: 1 error(s) on assignment of multiparameter attributes
    from /Users/david/.rvm/gems/ruby-1.9.3-p0/gems/validates_timeliness-3.0.8/lib/validates_timeliness/extensions/multiparameter_handler.rb:63:in `execute_callstack_for_multiparameter_attributes_with_timeliness'
    from /Users/david/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/attribute_assignment.rb:122:in `assign_multiparameter_attributes'
    from /Users/david/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/attribute_assignment.rb:98:in `assign_attributes'
    from /Users/david/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.2.1/lib/active_record/base.rb:495:in `initialize'
    from (irb):2:in `new'

I'm using version 3.0.8 of the plugin on Rails 3.2.1

Not validating invalid dates

I have the plugin setup with:

ValidatesTimeliness.setup do | config |
config.use_plugin_parser = true
config.enable_date_time_select_extension!
config.extend_orms = [ :active_record ]
end

in an initializer. In my model I have:
validates_datetime :start_date

However, when I enter a date into the Rails datetime selectors, like Feb 31, 2010, instead of throwing a validation error, it just sets the date to March 3, 2010. Shouldn't the validator catch this?

validates :timeliness

When I added this for validation it given invalid date error.

validates :published_at, :timeliness => {:type => :date}

Any Reasons?

No method error

This is what I have in my model.

validates_datetime :event_date, :on_or_after => Time.now, :on_or_before_message => "Event date/time must be in the future."

I am on rails 2.3.5 and I see this error

undefined method `validates_datetime' for #Class:0x7f55bbf394c8

RAILS_ROOT: /home//Apps/pj
Application Trace | Framework Trace | Full Trace

/usr/lib/ruby/gems/1.8/gems/searchlogic-2.4.19/lib/searchlogic/named_scopes/conditions.rb:81:in method_missing' /usr/lib/ruby/gems/1.8/gems/searchlogic-2.4.19/lib/searchlogic/named_scopes/association_conditions.rb:19:inmethod_missing'
/usr/lib/ruby/gems/1.8/gems/searchlogic-2.4.19/lib/searchlogic/named_scopes/association_ordering.rb:27:in method_missing' /usr/lib/ruby/gems/1.8/gems/searchlogic-2.4.19/lib/searchlogic/named_scopes/ordering.rb:30:inmethod_missing'
/usr/lib/ruby/gems/1.8/gems/searchlogic-2.4.19/lib/searchlogic/named_scopes/or_conditions.rb:28:in method_missing' /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1959:inmethod_missing_without_paginate'
/usr/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.11/lib/will_paginate/finder.rb:170:in method_missing' /home//Apps/pj/app/models/event.rb:17 /home//Apps/pj/app/controllers/events_controller.rb:12:inindex'

Non helpful error message when translations are missing

If I set the locale to :"pt-BR", which does not have validate_timeliness default configuration, on every validation I get this error: "restriction 'after' value was invalid", which obviously is not what is wrong.

The fact is that validate_timeliness_of formats are missing from the locale.yml file and since everything is being rescued, this turns to be very hard to debug and find out.

Rails 3 error

Getting this error when saving some records via the seeds file.

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
[PROJECT_GEM_PATH]/validates_timeliness-3.0.0.beta/lib/validates_timeliness/attribute_methods.rb:8:in define_timeliness_methods' [PROJECT_GEM_PATH]/validates_timeliness-3.0.0.beta/lib/validates_timeliness/orms/active_record.rb:8:indefine_attribute_methods'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/attribute_methods.rb:51:in respond_to?' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/base.rb:1548:inblock in attributes='
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/base.rb:1544:in each' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/base.rb:1544:inattributes='
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/base.rb:1411:in initialize' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/reflection.rb:173:innew'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/reflection.rb:173:in build_association' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/associations/association_collection.rb:512:inbuild_record'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/associations/association_collection.rb:119:in build' [PROJECT_GEM_PATH]/friendly_id-3.1.6/lib/friendly_id/active_record_adapter/slugged_model.rb:49:inbuild_a_slug'
[PROJECT_GEM_PATH]/activesupport-3.0.0/lib/active_support/callbacks.rb:429:in _run_save_callbacks' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/callbacks.rb:277:increate_or_update'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/persistence.rb:56:in save!' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/validations.rb:49:insave!'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/attribute_methods/dirty.rb:30:in save!' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/transactions.rb:242:inblock in save!'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/transactions.rb:289:in block in with_transaction_returning_status' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:139:intransaction'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/transactions.rb:204:in transaction' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/transactions.rb:287:inwith_transaction_returning_status'
[PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/transactions.rb:242:in save!' [PROJECT_GEM_PATH]/activerecord-3.0.0/lib/active_record/validations.rb:34:increate!'
[APP_ROOT]/db/seeds.rb:229:in `block in <top (required)>'

The model that im trying to save does not have any date validations at all, nor does it have any date fields at all.

undefined method 'validates_datetime'

I've followed the directions on here and installed the gem validates_timeliness, however I get the error "undefined method 'validates_datetime'" when I use that for model validations. The error shows up in my new view. What's strange is that it works fine in test (have written failing rspec tests and gotten them to pass using validates_datetime) and it works in the console (dev). Have searched at length online, and I'm sure I've done something foolish with the install, but would really appreciate any advice. Thanks

undefined method `to_time' for nil:NilClass

Hi!

undefined method `to_time' for nil:NilClass

I becomes this error if I check a date. If the date attribute is nil then this error is thrown. So I have to check first if the attribute is not nil?

Here the last three trace lines...
activesupport (3.0.3) lib/active_support/whiny_nil.rb:48:in method_missing' validates_timeliness (3.0.3) lib/validates_timeliness/conversion.rb:62:inparse'
validates_timeliness (3.0.3) lib/validates_timeliness/validator.rb:44:in `validate_each'

deprecation warnings for rails 3.0

running version (3.0.0.beta.3) of validates_timeliness, i get the following deprecation warning when using validates_date:

/Library/Ruby/Gems/1.8/gems/activerecord-3.0.0/lib/active_record/attribute_methods/time_zone_conversion.rb:56: warning: Object#type is deprecated; use Object#class

if it helps, i'm setting the date for a model object in the unit test in the following manner: Date.civil(y=1997, m=1, d=1)

The Rails date_helper can choke when validates_timeliness finds a date to be invalid.

I am using Rails 2.3.5 and validates_timeliness 2.3.2 (there are reasons I cannot upgrade to Rails 3 at this time).

If the date is fine, then everything is fine.

If the date is not fine (in this example, the date is 11-31-2010), then date_select will not work when the update method re-renders the form. I should mention that the errors are correct, and the date is marked as invalid. I am using "ValidatesTimeliness.enable_datetime_select_extension!" in my environment.rb. The problem is that in the select_year method of the date_helper, it sees the year from validates_timeliness as "2010," and then breaks because it tries to subtract 5 from a string ("2010").

This break happens when reading from a TimelinessDateTime struct as defined in instance_tag.rb, so I don't know if it would make sense to just have that struct give out ints, or if that would cause other problems.

I haven't seen many errors like this, so I am wondering if perhaps I am using the wrong version of the gem. The documentation says validates_timeliness 2.3.2 works with Rails 2.x, but I wonder if there is further granularity to it. At the very least, I would appreciate any advice that seems obvious to others. Thank you.

Virtual attributes

I have a virtual attribute on an ActiveRecord model:

class Post < ActiveRecord::Base
  attr_accessor :some_date
  validates_date :some_date
end

The validates_timeliness gem works fine on database attributes, but when trying to validate a virtual attribute as above, I get the following error when trying to validate an instance of Post:

NoMethodError (undefined method `type' for nil:NilClass):

activesupport (3.1.0) lib/active_support/whiny_nil.rb:48:in `method_missing'
activerecord (3.1.0) lib/active_record/attribute_methods/time_zone_conversion.rb:62:in `create_time_zone_conversion_attribute?'
validates_timeliness (3.0.7) lib/validates_timeliness/orm/active_record.rb:16:in `timeliness_attribute_timezone_aware?'
validates_timeliness (3.0.7) lib/validates_timeliness/validator.rb:85:in `timezone_aware?'
validates_timeliness (3.0.7) lib/validates_timeliness/validator.rb:42:in `validate_each'
activemodel (3.1.0) lib/active_model/validator.rb:153:in `block in validate'
activemodel (3.1.0) lib/active_model/validator.rb:150:in `each'
activemodel (3.1.0) lib/active_model/validator.rb:150:in `validate'
activesupport (3.1.0) lib/active_support/callbacks.rb:302:in `_callback_before_108387'
activesupport (3.1.0) lib/active_support/callbacks.rb:597:in `_run_validate_callbacks'
activesupport (3.1.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
activemodel (3.1.0) lib/active_model/validations.rb:212:in `run_validations!'
activemodel (3.1.0) lib/active_model/validations/callbacks.rb:53:in `block in run_validations!'
activesupport (3.1.0) lib/active_support/callbacks.rb:400:in `block in _run_validation_callbacks'
activesupport (3.1.0) lib/active_support/callbacks.rb:207:in `block in _conditional_callback_around_108250'
...

Add formats

i'm trying set a new date format..

config.parser,add_formats(:date, 'dd/mm/yyyy')

i'm still get error of invalid date.

ActiveRecord shim doesn't seem to be working...

If I define a validation...

validates_date :completed_on, :before => 10.years.ago, :allow_nil => true

... and set completed_on to Date.today, validation happens successfully and I get an error. If I set completed_on to 'foo', validation passes with no errors. By the time the validator gets the value of completed_on, it's nil, not 'foo'.

I've run 'rails generate validates_timeliness:install' and uncommented 'config.extend_orms = [ :active_record ]' in config/initializers/validates_timeliness.rb.

I'm running Rails 3.0.3, ruby 1.8.7-p174 on OS X 10.6.6 with active_record 3.0.3, validates_timeliness 3.0.4, and timeliness 0.3.3. I do have a lot of other gem dependencies in the project, maybe one of them is interfering?

Any help is greatly appreciated!

datetime checks in rails views

Dears,

i was looking for Date and DateTime Checks in my Views :

to check if Time.now.before? @post.publish_at or Time.now.after? @post.publish_at or any other validations available

Non descriptibe error message on rspec matchers when missing some translations keys

The plugin was woking very nice, but I changed the default locale to :es in enviroment.rb:
config.i18n.default_locale = :es

The when I ran my specs I got this error whenusing should validate_date and should validate_time:

"private method `gsub' called for nil:NilClass"

after half an hour I realize the real problem was that these keys where not defined in es.yml:

validates_timeliness:
error_value_formats:
date: '%Y-%m-%d'
time: '%H:%M:%S'
datetime: '%Y-%m-%d %H:%M:%S'

When this happend those helpers should give you a more readable message.

Date depending of other date (re-open of #38)

As posted as comment for closed issue #38, this code is not working:

My whole validation looks like:
validates_date :end_date,
:on_or_after => :start_date,
:on_or_before => lambda { |r| r.start_date + 90.days },
:unless => "start_date.blank?"

But dates that are more than 90 days in the future are accepted.

Unexpected behaviour: validate_date accepts 31/09/2010

hi there
I'm a ruby/rails/hobo newbie, so it's possible i'm doing something to affect this, but as far as I can see I have validates_timeliness installed correctly ...

validates_date :mydate, :before (2.years.ago) # works as expected -
validates_date :mydate # lets 31/09/2010 through... invalid_date exception in rails
thanks for considering this
paul

Mongoid 2.3.0 undefined method `reload'

Just tried upgrading to Mongoid 2.3.0 and am getting the following error on startup:

undefined method `reload' for module `Mongoid::Document'

It looks like there were some changes to how documents are reloaded in the latest Mongoid, but I've been unable to figure out how they are affecting validates_timeliness

mongoid/mongoid@16d6f2f

shouldn't the :type value be a symbol?

sorry if this is bull but in the readme it says:
validates :date_of_birth, :timeliness => {:on_or_before => lambda { Date.today }, :type => date}

shouldn't it rather be with date being a symbol:
validates :date_of_birth, :timeliness => {:on_or_before => lambda { Date.today }, :type => :date}

Fails in autospec, but works in spec

If I run spec, everything runs perfectly. (Did the config gem in environment.rb, added to Gemfile, installed gem).

Running Rspec, I get this error (undefined method validates_datetime):

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/bin/spec --autospec /Users/Hao/Documents/Programming/Projects/Taask/spec/controllers/pages_controller_spec.rb /Users/Hao/Documents/Programming/Projects/Taask/spec/controllers/tasks_controller_spec.rb /Users/Hao/Documents/Programming/Projects/Taask/spec/models/task_spec.rb /Users/Hao/Documents/Programming/Projects/Taask/spec/helpers/tasks_helper_spec.rb /Users/Hao/Documents/Programming/Projects/Taask/spec/models/user_spec.rb /Users/Hao/Documents/Programming/Projects/Taask/spec/controllers/user_sessions_controller_spec.rb /Users/Hao/Documents/Programming/Projects/Taask/spec/controllers/users_controller_spec.rb -O spec/spec.opts
/Library/Ruby/Gems/1.8/gems/bundler-1.0.0/lib/bundler/runtime.rb:132: warning: Insecure world writable dir /Users/Hao/Documents/Programming/Projects in PATH, mode 040777
/Library/Ruby/Gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:1994:in method_missing': undefined methodvalidates_datetime' for #Class:0x1037c76b8 (NoMethodError)
from /Users/Hao/Documents/Programming/Projects/Taask/app/models/task.rb:12
from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:158:in require' from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:158:inrequire'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:265:in require_or_load' from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:224:independ_on'
from /Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:136:in require_dependency' from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:414:inload_application_classes'
from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:413:in each' from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:413:inload_application_classes'
from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:411:in each' from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:411:inload_application_classes'
from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:197:in process' from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:113:insend'
from /Library/Ruby/Gems/1.8/gems/rails-2.3.8/lib/initializer.rb:113:in run' from /Users/Hao/Documents/Programming/Projects/Taask/config/environment.rb:9 from /Users/Hao/Documents/Programming/Projects/Taask/spec/spec_helper.rb:4:inrequire'
from /Users/Hao/Documents/Programming/Projects/Taask/spec/spec_helper.rb:4
from /Users/Hao/Documents/Programming/Projects/Taask/spec/models/task_spec.rb:1:in require' from /Users/Hao/Documents/Programming/Projects/Taask/spec/models/task_spec.rb:1 from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:15:inload'
from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:15:in load_files' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:14:ineach'
from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/lib/spec/runner/example_group_runner.rb:14:in load_files' from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/lib/spec/runner/options.rb:134:inrun_examples'
from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/lib/spec/runner/command_line.rb:9:in `run'
from /Library/Ruby/Gems/1.8/gems/rspec-1.3.1/bin/spec:5

multiparameter handling support for Mongoid

I have the equivalent of the plugin's multiparameter extension working with Mongoid, currently just monkeypatching Mongoid's multiparameter attribute handling in my app with code trivially adapted from your AR version.

Aside from the fact that it'd be nice if 2.0.0 would make it to release stage so we'd know our moving targets better (I just made a plea for some roadmap transparency on their mailing list the other day...), I'd be happy to work this into a patch with tests for validates_timeliness if you let me know how you'd like to approach the configuration aspect. Perhaps just have it loaded by enable_multiparameter_extension! if extend_orms includes :mongoid?

problem with select_date :include_blank and not completed selection (ex. select only year)

Hi!

I've a problem with select_date and not completed selection (ex. select only year and post)
This doesn't go well because plugin doesn't handle a nil value from ValidatesTimeliness::Formats.parse(raw_value, :datetime) on ValidatesTimeliness::ActionView::InstanceTag::value_with_timeliness method (validates_timeliness/lib/validates_timeliness/action_view/instance_tag.rb:31)

This generates an error:
ActionView::TemplateError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.

Backtrace:
/home/giulio/myproject/trunk/vendor/plugins/validates_timeliness/lib/validates_timeliness/action_view/instance_tag.rb:42:in value' /home/giulio/myproject/trunk/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb:920:indatetime_selector_without_timeliness'
/home/giulio/myproject/trunk/vendor/plugins/validates_timeliness/lib/validates_timeliness/action_view/instance_tag.rb:28:in datetime_selector' /home/giulio/myproject/trunk/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb:907:into_date_select_tag_without_error_wrapping'
/home/giulio/myproject/trunk/vendor/rails/actionpack/lib/action_view/helpers/active_record_helper.rb:268:in to_date_select_tag' /home/giulio/myproject/trunk/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb:186:indate_select'
/home/giulio/myproject/trunk/vendor/rails/actionpack/lib/action_view/helpers/date_helper.rb:964:in date_select' /home/giulio/myproject/trunk/app/views/people/_form.html.erb:40:in_run_erb_app47views47people47_form46html46erb_locals_f_form_object'
/home/giulio/myproject/trunk/app/views/people/_edit_form.html.erb:6:in _run_erb_app47views47people47_edit_form46html46erb_locals_edit_form_object' /home/giulio/myproject/trunk/app/views/people/_edit_form.html.erb:5:in_run_erb_app47views47people47_edit_form46html46erb_locals_edit_form_object'
/home/giulio/myproject/trunk/app/views/people/edit.html.erb:2:in _run_erb_app47views47people47edit46html46erb' /home/giulio/myproject/trunk/app/controllers/people_controller.rb:93:inupdate'
/home/giulio/myproject/trunk/app/controllers/people_controller.rb:84:in `update'

I fix this problem with a check

time_array = ValidatesTimeliness::Formats.parse(raw_value, :datetime)
unless time_array.nil?
TimelinessDateTime.new(time_array[0..5])
else
TimelinessDateTime.new(
[0,0,0,0,0,0])
end

But this fills wrong the year select with values around year 0 (-2 -1 0 1 2...) because it relies on base year.

Ty

G.

Value of message == Value used in validation ??? Possible?

Hello,

In the validation message I would like to use the same value that was used in validation, as a parameter. Is this possible?

since,:advance_minutes will be equal to obj.unity.unity_preference.time_advance_reservation_in_minutes

Best regards,
Fernando.

:message ignored by validates_date

Specifying a message, for example

validates_date :end_date, :after => :start_date, :message => "Something is fack to brunt here"

The error message will still display the message in the locales translation file (or complain about a missing translation)

This is using the mongoid ODM, I do not know if ActiveRecord has the same problem.

validates_timeliness validates unvalid dates?

Hi there!
Using Rails 2.3.5 & Ruby 1.8.7 I've tried this plugin in order to unvalidate dates like 31-Feb
Here is part of my form:

<%= f.label :birthdate %><br />
<%= f.date_select :birthdate,
                  :start_year => Time.now.year - 100, 
                  :end_year => Time.now.year,
                  :order => [:day, :month, :year],
                  :prompt => true %>

and my model :

class User < ActiveRecord::Base
attr_accessible :birthdate
validates_date :birthdate, :allow_nil => true
end

However, it is still validate 31-Feb and returns 03-03. Moreover, if I display, for example : Day-Month-2001 in my form it returns 01-01-2001. (I would like this to be unvalid as the validates_date_time plugin provides)
I tried these using validates_timeliness as a gem and plugin
I really think I miss something... and would be very pleased if someone can help. Thank you!

ArgumentError: invalid date

Hi,

Model:

class Inspection
  include Mongoid::Document
  field :date, :type => Date
  validates_date :date, :allow_blank => true
end

Rails console:

 >Inspection.new(:date => "crap")
 ArgumentError: invalid date

It seems the shim does not work for my version of:

  • rails: 3.0.10
  • mongoid: 2.2.0
  • validates_timeliness: 3.0.6

Unexpected Behavior: validates_time Accepts Invalid 12 Hour Times

The current implementation of validates_time accepts 12 hour times that are invalid, though logically convertible to an appropriate time. For instance, the times 0am through 24am are all accepted as valid with 13am interpreted as 1pm even though 13am is an invalid 12-hour time. This is not what I would expect though, I believe that this behavior is reasonable it is not mentioned at all in the documentation that this is the case.

A note in the documentation about this would be helpful to others. Alternatively rejecting those invalid times would in my opinion be less of a surprise in lieu of specifying that this behavior is considered valid though inconsistent with 12-hour time conventions.

no translation with restrictions

Everything works fine with the default language en.
But if I use another language (like de), translation for restrictions like 'before' will not be used. So I get 'myDateTime restriction 'before' value was invalid'. All translations of readme file are installed.
I am using the current version 2.2.2.

exception re: generated_methods when using authlogic

I wonder if there is some inaccurate assumption being made about the status of @generated_methods ?

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.include?):
/Library/Ruby/Gems/1.8/gems/adzap-validates_timeliness-2.1.0/lib/validates_timeliness/active_record/attribute_methods.rb:62:in define_attribute_methods' authlogic (2.1.1) lib/authlogic/acts_as_authentic/session_maintenance.rb:73:insave_without_session_maintenance'
authlogic (2.1.1) lib/authlogic/session/callbacks.rb:83:in save_record' authlogic (2.1.1) lib/authlogic/session/priority_record.rb:30:insave_record'
authlogic (2.1.1) lib/authlogic/session/persistence.rb:60:in persisting?' authlogic (2.1.1) lib/authlogic/session/persistence.rb:39:infind'
app/controllers/application_controller.rb:22:in current_user_session' app/controllers/application_controller.rb:27:incurrent_user'
app/controllers/application_controller.rb:32:in require_user' /Library/Ruby/Gems/1.8/gems/newrelic_rpm-2.9.4/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:138:inperform_action'
/Library/Ruby/Gems/1.8/gems/newrelic_rpm-2.9.4/lib/new_relic/agent/method_tracer.rb:62:in trace_method_execution_with_scope' /Library/Ruby/Gems/1.8/gems/newrelic_rpm-2.9.4/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:122:inperform_action'
/Library/Ruby/Gems/1.8/gems/newrelic_rpm-2.9.4/lib/new_relic/agent/method_tracer.rb:38:in trace_method_execution_no_scope' /Library/Ruby/Gems/1.8/gems/newrelic_rpm-2.9.4/lib/new_relic/agent/instrumentation/controller_instrumentation.rb:117:inperform_action'

Syntax typo in the README

You have a syntax typo in the README file:

validates_date :date_of_birth :before => lambda { 18.years.ago },
                              :before_message => "must be at least 18 years old"

is missing a comma after :date_of_birth

Improve ActiveModel support

class Test
 attr_accessor :valid_from
 attr_accessor :valid_to
 include  ::ActiveModel::Validations
end

class TestWithCasting
 attr_reader :valid_from, :valid_from_before_type_cast
 def valid_from=(v)
  @valid_from_before_type_cast = v
  @valid_from = Date.parse(v) # ActiveRecord::ConnectionAdapters::Column.string_to_date(v)
 end

 include  ::ActiveModel::Validations
end

It would be nice to have a support backed up by few test to such use cases. Currently there are many troubles with making it work well with validations from validates_timeliness.

Date depending of other date

Hi,

would it be possible to realize something like that: I have a start date and a end date. The end date must be before start date + 90.days.

I tried:
:on_or_before => lambda { :start_date + 90.days },
:on_or_before => lambda { self.start_date + 90.days },

But non of them worked.

Regards,
sewid

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.