Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Way to validate date/time components #4

Open
Matt888 opened this issue Feb 17, 2014 · 2 comments
Open

Way to validate date/time components #4

Matt888 opened this issue Feb 17, 2014 · 2 comments

Comments

@Matt888
Copy link

Matt888 commented Feb 17, 2014

I have a field called start_at, and I'm using start_at_date in a form. If the user doesn't enter a valid date, it throws an exception "invalid date". Is it possible to use validation instead to prompt the user to enter a valid date?

@shekibobo
Copy link
Owner

What are you currently using for validation? I use date_validator when validating dates. In any case, however you decide to validate your dates, you can validate the split fields in exactly the same way as the primary field.

validates :start_at, :start_at_date, :start_at_time, presence: true

However, if you're trying to just get the user to consistently input the correct format, I would recommend using some kind of datepicker interface. The jQueryUI datepicker will work pretty well in most cases for just a date.

If you're looking for a combined datetime picker, I've been looking at this one as one of the friendlier mixed pickers I've seen.

@pwim
Copy link

pwim commented Nov 28, 2014

I ran into this issue as well. We're using a javascript plugin to let the users pick the date, but they can still edit the text field themselves, which I think is a must from a UX perspective.

The issue is with the way the accessors are defined:

define_method("#{attr}_date=") do |date|
  return unless date.present?
  date = Date.parse(date.to_s)
  self.send("#{attr}=", self.send("#{attr}_or_new").change(year: date.year, month: date.month, day: date.day))
end

So if the user enters something like "2014" for the date part, this code will do Date.parse("2014"), which will raise an exception. Maybe it is better to rescue the ArgumentError in this method?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants