开发者

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

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?


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.


I hope this helps.

validates :date_of_birth, format: { with: /^\d{4}-\d{2}-\d{2}$/, multiline: true }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜