Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate the date such that it is after today in Rails?

I have an Active Record model that contains attributes: expiry_date. How do I go about validating it such that it is after today(present date at that time)? I am totally new to Rails and ruby and I couldn't find a similar question answering exactly this?

I am using Rails 3.1.3 and ruby 1.8.7

like image 491
coding_pleasures Avatar asked Dec 14 '11 22:12

coding_pleasures


People also ask

How do you validate a date field?

The date in the date field has to be after today's date and not in the past. It also has to be within 30 days from today's date. So if today is 15/01/2013, then the form can only accept any date within 30 days after the 15/02/2013, so the 14/04/2007 plus 30 days!

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is a date validation?

date of validation means the date when the Referred Party has successfully validated his/her identity and fully completed the on-boarding procedures.

What is custom validation in rails?

Published Feb 02, 2018. Validation is one of the core features which rails provides. There are plenty of built in validation helpers there which helps validating our form inputs or user attributes.


2 Answers

Your question is (almost) exactly answered in the Rails guides.

Here's the example code they give. This class validates that the date is in the past, while your question is how to validate that the date is in the future, but adapting it should be pretty easy:

class Invoice < ActiveRecord::Base   validate :expiration_date_cannot_be_in_the_past    def expiration_date_cannot_be_in_the_past     if expiration_date.present? && expiration_date < Date.today       errors.add(:expiration_date, "can't be in the past")     end   end     end 
like image 93
apneadiving Avatar answered Oct 07 '22 18:10

apneadiving


Here's the code to set up a custom validator:

#app/validators/not_in_past_validator.rb class NotInPastValidator < ActiveModel::EachValidator   def validate_each(record, attribute, value)     if value.blank?       record.errors.add attribute, (options[:message] || "can't be blank")     elsif value <= Time.zone.today       record.errors.add attribute,                         (options[:message] || "can't be in the past")     end   end end 

And in your model:

validates :signed_date, not_in_past: true 
like image 42
Dan Kohn Avatar answered Oct 07 '22 19:10

Dan Kohn