Trying to validate a date - ruby-on-rails

I have a form where i'm trying to validate that a field called "birthday" is not blank, and that the date is a valid date format that the Chronic gem can parse. I always get the error message "Birthday is invalid". I've been trying a simple format "10/10/2010".
How can i validate that the birthday field is of a format that chronic can parse?
User.rb model
class User < ActiveRecord::Base
validates :birthday, :presence => true
validate :birthday_is_date
validate :position, :presence => true
# validate the birthday format
def birthday_is_date
errors.add(:birthday ,Chronic.parse(birthday)) # testing to see the value of :birthday
errors.add(:birthday, "is invalid test message") if ((Chronic.parse(:birthday) rescue ArgumentError) == ArgumentError)
end
end
contacts_controller.rb
# POST /contacts/1/edit
# actually updates the users data
def update_user
#userProfile = User.find(params[:id])
respond_to do |format|
if #userProfile.update_attributes(params[:user])
format.html {
flash[:success] = "Information updated successfully"
redirect_to(profile_path)
}
else
format.html {
flash[:error] = resource.errors.full_messages
render :edit
}
end
end
end

Your birthday_is_date validation always adds an error on the first line. It should be written as follows:
def birthday_is_date
errors.add(:birthday, "is invalid") unless Chronic.parse(birthday)
end

try this
install validates_date_time gem
you can pass validation for date, for example
class Person < ActiveRecord::Base
validates_date :date_of_birth
validates_time :time_of_birth
validates_date_time :date_and_time_of_birth
end
Use :allow_nil to allow the value to be blank.
class Person < ActiveRecord::Base
validates_date :date_of_birth, :allow_nil => true
end
Source : https://github.com/smtlaissezfaire/validates_date_time

From chronic.rubyforge.org:
Chronic uses Ruby’s built in Time class for all time storage and
computation. Because of this, only times that the Time class can
handle will be properly parsed. Parsing for times outside of this
range will simply return nil. Support for a wider range of times is
planned for a future release.
Time zones other than the local one are not currently supported.
Support for other time zones is planned for a future release.
From Date validation in Ruby using the Date object:
A simple validate function
One way to test for a valid date is to try to create a Date object. If
the object is created, the date is valid, and if not, the date is
invalid. Here is a function that accepts year, month, and day, then
returns true if the date is valid and false if the date is invalid.
def test_date(yyyy, mm, dd)
begin
#mydate = Date.new(yyyy, mm, dd)
return true
rescue ArgumentError
return false
end
end
From the accepted answer of How do I validate a date in rails?:
If you're looking for a plugin solution, I'd checkout the
validates_timeliness plugin. It works like this (from the github
page):
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
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.

Related

Order/precedence of rails validation checks

I'm trying to get my head around the order/precedence with which Rails processes validation checks. Let me give an example.
In my model class I have these validation checks and custom validation methods:
class SupportSession < ApplicationRecord
# Check both dates are actually provided when user submits a form
validates :start_time, presence: true
validates :end_time, presence: true
# Check datetime format with validates_timeliness gem: https://github.com/adzap/validates_timeliness
validates_datetime :start_time
validates_datetime :end_time
# Custom method to ensure duration is within limits
def duration_restrictions
# Next line returns nil if uncommented so clearly no start and end dates data which should have been picked up by the first validation checks
# raise duration_mins.inspect # Returns nil
# Use same gem as above to calculate duration of a SupportSession
duration_mins = TimeDifference.between(start_time, end_time).in_minutes
if duration_mins == 0
errors[:base] << 'A session must last longer than 1 minute'
end
if duration_mins > 180
errors[:base] << 'A session must be shorter than 180 minutes (3 hours)'
end
end
The problem is that Rails doesn't seem to be processing the 'validates presence' or 'validates_datetime' checks first to make sure that the data is there in the first place for me to work with. I just get this error on the line where I calculate duration_mins (because there is no start_time and end_time provided:
undefined method `to_time' for nil:NilClass
Is there a reason for this or have I just run into a bug? Surely the validation checks should make sure that values for start_time and end_time are present, or do I have to manually check the values in all of my custom methods? That's not very DRY.
Thanks for taking a look.
Rails will run all validations in the order specified even if any validation gets failed. Probably you need to validate datetime only if the values are present.
You can do this in two ways,
Check for the presence of the value before validating,
validates_datetime :start_time, if: -> { start_time.present? }
validates_datetime :end_time, if: -> { end_time.present? }
Allows a nil or empty string value to be valid,
validates_datetime :start_time, allow_blank: true
validates_datetime :end_time, allow_blank: true
Simplest way, add this line right after def duration_restrictions
return if ([ start_time, end_time ].find(&:blank?))
Rails always validate custom method first.

How to set the order of validation methods ruby on rails?

I am a Ror beginner. There is a model Lecture, I want to validate the format of start time and end time firstly, and then check if the end time is after start time. It works well when the format is valid but once the format is wrong it comes with: undefined method `<' for nil:NilClass. How to makes start_must_be_before_end_time triggered only when the format is valid? Thanks!
Here is the code:
class Lecture < ActiveRecord::Base
belongs_to :day
belongs_to :speaker
validates :title, :position, presence: true
validates :start_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
message: "Incorrect time format" }
validates :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
message: "Incorrect time format" }
validate :start_must_be_before_end_time
private
def start_must_be_before_end_time
errors.add(:end_time, "is before Start time") unless start_time < end_time
end
end
There are no guarantees on the order of validations that are defined by validates methods. But, the order is guaranteed for custom validators that are defined with validate method.
From docs:
You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
Alternatively
You can only run your validation method if all other validations pass:
validate :start_must_be_before_end_time, :unless => Proc.new { |obj| obj.times_valid? }
# Then, define `times_valid?` method and check that start_time and end_time are valid
You can go another way:
errors.add(:end_time, "is before Start time") unless start_time.nil? || end_time.nil? || start_time < end_time

Rails validation not failing

I have the following validation on a model field:
validates :invoice_date, :presence => true, :unless => Proc.new { |invoice| invoice.invoice_date.future? }
It looks pretty simple, but it doesn't work. There is no error thrown if the date is in the future. And the Proc indeed returns false in that case.
Any idea why isn't there any validation error shown?
The 'unless' condition is for deciding if the validation should run or not, not if it should succeed or fail. So your validation is essentially saying "validate the presence of invoice_date, unless invoice_date is in the future in which case don't validate its presence" (which makes no sense)
It sounds like you want two validations, presence and date fencing.
validate :invoice_date_in_past
def invoice_date_in_past
if invoice_date.future?
errors.add(:invoice_date, 'must be a date in the past')
end
end
validates :invoice_date, :presence => true
validate :is_future_invoice_date?
private
def is_future_invoice_date?
if invoice_date.future?
errors.add(:invoice_date, 'Sorry, your invoice date is in future time.')
end
end
Presence true simply ensures, invoice_date must be present.
for validating whether the date is a future date or not we have specified a custom validation method.(is_future_invoice_date?)
This method, will add error message against our invoice_date attribute if the date is of future date.
More info here: http://guides.rubyonrails.org/active_record_validations.html#custom-methods
Try like that :--
validate check_invoice_date_is_future
def check_invoice_date_is_future
if invoice_date.present?
errors.add(:invoice_date, "Should not be in future.") if invoice_date.future?
else
errors.add(:invoice_date, "can't be blank.")
end
end

Rails: how to validate an object field's value before save?

I'm writing a Redmine plugin that should check if some fields of an Issue are filled depending on values in other fields.
I've written a plugin that implements validate callback, but I don't know how to check field values which are going to be saved.
This is what I have so far:
module IssuePatch
def self.included(receiver)
receiver.class_eval do
unloadable
validate :require_comment_when_risk
protected
def require_comment_when_risk
risk_reduction = self.custom_value_for(3)
if risk_reduction.nil? || risk_reduction.value == 0
return true
end
comment2 = self.custom_value_for(4)
if comment2.nil? || comment2.value.empty?
errors.add(:comment2, "Comment2 is empty")
end
end
end
end
end
The problem here is that self.custom_value_for() returns the value already written to the DB, but not the one that is going to be written, so validation doesn't work. How do I check for the value that was passed from the web-form?
Any help will be greatly appreciated.
The nice thing about rails is that in your controller you don't have to validate anything. You are suppose to do all of this in your model. so in your model you should be doing something like
validates :value_that_you_care_about, :numericality => { :greater_than_or_equal_to => 0 }
or
validates :buyer_name, presence: true, :length => {:minimum => 4}
or
validates :delivery_location, presence: true
If any of these fail this will stop the object from being saved and if you are using rails scaffolding will actually highlight the field that is incorrect and give them and error message explaining what is wrong. You can also write your own validations such as
def enough_red_flowers inventory
if inventory.total_red_flowers-self.red_flower_quantity < 0
self.errors.add(:base, 'There are not enough Red Flowers Currently')
return false
end
inventory.total_red_flowers = inventory.total_red_flowers-self.red_flower_quantity
inventory.save
true
end
To write your own custom message just follow the example of self.errors.add(:base, 'your message')
You can find more validations here
Better way it's create custom validator
class FileValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
# some logic for validation
end
end
then in model:
validates :file, file: true

Rails validation method comparing two fields?

My model has two fields that i want to compare to each other as part of the validation. I want to be sure end_time is after start_time. I have written a validation method to compare them, but I must be doing something wrong, because the values are always nil. Can someone help?
class LogEntry < ActiveRecord::Base
validates :start_time, :presence => { :message => "must be a valid date/time" }
validates :end_time, :presence => {:message => "must be a valid date/time"}
validate :start_must_be_before_end_time
def start_must_be_before_end_time
errors.add(:start_time, "must be before end time") unless
start_time > end_time
end
end
gets the error
undefined method `>' for nil:NilClass
So, start_time and/or end_time are nil. I thought I was following the many examples I found, but apparently not. What am I missing?
Thanks.
My best guess is you need your method to look like this:
private
def start_must_be_before_end_time
errors.add(:start_time, "must be before end time") unless
start_time < end_time
end
(Also, notice the < rather than > (or change to if and >=)
If this doesn't work then you should also check that start_time and end_time are being defined correctly in the controller as there can be funny things happen if the time is created across more than one form element.
With Rails 7 ComparisonValidator
Rails 7 has added the ComparisonValidator which allows you to use the convenience method validates_comparison_of like so:
class LogEntry < ActiveRecord::Base
validates_comparison_of :start_time, less_than: :end_time
# OR
validates_comparison_of :end_time, greater_than: :start_time
end
Find out more here: https://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html#method-i-validates_comparison_of
You need to check for presence yourself (and skip the validation step if not present).
def start_must_be_before_end_time
return unless start_time and end_time
errors.add(:start_time, "must be before end time") unless start_time < end_time
end
Prints either "must be a valid date/time" OR "start time must be before end time".
Alternative
def start_must_be_before_end_time
valid = start_time && end_time && start_time < end_time
errors.add(:start_time, "must be before end time") unless valid
end
Prints "start time must be a valid date/time" AND "start time must be before end time" if start_time or end_time isn't set.
Personal preference for the first, since it only shows what the user did wrong. The latter is like many websites which just load off 20 lines of error text onto the user just because the programmer thought it would be nice to see every validation result. Bad UX.
Clean and Clear (and under control?)
I find this to be the clearest to read:
In Your Model
# ...
validates_presence_of :start_time, :end_time
validate :end_time_is_after_start_time
# ...
#######
private
#######
def end_time_is_after_start_time
return if end_time.blank? || start_time.blank?
if end_time < start_time
errors.add(:end_time, "cannot be before the start time")
end
end
Ruby on Rails 7.0 supports validates_comparison_of like this
validates :start_time, comparison: { less_than: :end_date }
You can use validates_timeliness gem https://github.com/adzap/validates_timeliness
start_time.to_i < end_time.to_ishould fix it. You are trying to compare datetime but for some reason it can't, so convert them to int before comparing.

Resources