I think i might be dreaming, but i think i read somewhere that you can validate the type of an attribute of an object before you save it? Something
like validates :transaction_date, :type => Date
and that will make sure that its a date?
Is this possible in Rails 3.2? i am trying to find evidence of this on the net. i have already looked here at the rails api and i am going through the ActiveRecord support.
So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.
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.
A very common way to skip validation is by keeping the value for immediate attribute as 'true' for the UIComponents. Immediate attribute allow processing of components to move up to the Apply Request Values phase of the lifecycle. scenario: While canceling a specific action, system should not perform the validation.
As a complement to the other answers, note that you can define a custom validator to let you use exactly the syntax you proposed:
validates :transaction_date, :type => Date
as follows:
class TypeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, (options[:message] || "is not of class #{options[:with]}") unless
value.class == options[:with]
end
end
Of course, if you want to allow subclasses, you could change the test to use kind_of?
.
Rails doesn't support this directly; the closest it comes is probably validates_format_of, or supplying your own custom validator.
I think what you want is the validates_timeliness gem. It not only validates that something is a valid date, but you can specify whether it should be before or after today and various other date range checks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With