Closed khanhhd closed 1 year ago
Couple of things. The validation should be written as
validates_datetime :column_name, format: /yyyy[\/-]mm[\/-]dd\shh\:nn\:ss/, allow_blank: true
But specifically, the format
option is not meant to be a regexp but a Timeliness format string. The yyyy/mm/dd hh:nn:ss
is not a default format but you can add it as a custom format globally.
Try
Timeliness.add_formats(:datetime, 'yyyy/mm/dd hh:nn:ss')
see how that goes
put the Timeliness line in an initializer.
Hello @adzap , Thanks for your reply. I had tried with your code. But It seem does not work
#config/initializers/validates_timeliness.rb
ValidatesTimeliness.setup do |config|
config.extend_orms = [ :active_record ]
config.use_plugin_parser = true
Timeliness.add_formats(:datetime, 'yyyy/mm/dd hh:nn:ss')
end
#model.rb
validates_datetime :column_name, format: /yyyy[\/-]mm[\/-]dd\shh\:nn\:ss/, allow_blank: true
It does not accept anything even the value is 2011/11/11 11:11:11
or 2011-11-11 11:11:11
Ah sorry I should have been more explicit. After adding that format the validation becomes simply this
validates_datetime :column_name, allow_blank: true
Also for safety move the Timeliness.add_formats
call outside the setup do block.
@adzap I just want It accepts 2 formats yyyy-mm-dd hh:nn:ss
or yyyy/mm/dd hh:nn:ss
If we remove format option in model. It also accepts other types. Such as 11-11-2011 11:11:11
, 11/11/2011 11:11:11
That is not really supported directly in the validation. It is really necessary to be so restrictive on the format? How is the datetime being captured, web form?
It is read from CSV file, If it is web form then we can validate in client side :) Thanks for your help (y)
ah ok. you can never rely on client side validation alone, but restricting the format would be easier.
i wrote the following codes in the User class at models/user.rb.
validates_date :movedin_date, :allow_blank, :on_or_before => lambda { Date.current }, :format => %r@\d{4}/\d{2}/\d{2}@m
I want the format to be 'yyyy/mm/dd'. But, this is kind of difficult for me, so is it okay to add the following lilne in the initilizer?
Timeliness.add_formats(:date, 'yyyy/mm/dd')
ValidatesTimeliness.setup do |config|
:
end
Humi
yes that should be fine to add to the initializer
I have an issue with format option: my case is the field accepts 2 types
or
My code was:
The default value in migration is
2000-01-01 00:00:00
But It did not accept the value2017/11/11 11:11:11