Date of birth regex yyyy-mm-dd for rails app

本秂侑毒 提交于 2019-12-10 17:28:36

问题


I am creating a user signup form, and I am adding date of birth to the required fields.

I have scoured google, github and stackoverflow for a good date of birth (date) regex, and found this:

user.rb

DateRegex = /^\d{4}-\d{2}-\d{2}/

validates_format_of :date_of_birth, :with => DateRegex

new.html.erb

<%=label_tag :date_of_birth %>
<%=f.text_field :date_of_birth %> 

(I know that this will allow some bogus birth dates, but I prefer not to install anything like validate timeliness at this point.)

However, when testing the date of birth, it doesn't seem to enforce the 4-2-2 in the regex. It allows 2-2-2 sometimes, 2-4-2, 2-2-4, and it allows hyphens and slashes...help please?

Also, if necessary, how to I use 3 text fields and have it enter into one mysql date_of_birth column?


回答1:


You could always just use Date.parse to make your life a lot easier. If it can be parsed, it's probably a valid date:

validates_each :date_of_birth do |record, attr, value|
  begin
    Date.parse(value)
  rescue
    record.errors.add(attr, "Invalid date")
  end
end

This has the advantage of rejecting things like 99-99-99 and February 30th.



来源:https://stackoverflow.com/questions/6065048/date-of-birth-regex-yyyy-mm-dd-for-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!