出生日期正则表达式yyyy-mm-dd for rails app [英] Date of birth regex yyyy-mm-dd for rails app

查看:321
本文介绍了出生日期正则表达式yyyy-mm-dd for rails app的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个用户注册表单,我将生成的日期添加到必填字段中。



我已经在google,github和stackoverflow中找到了一个很好的日期的出生(日期)正则表达式,并发现:



user.rb

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

validates_format_of:date_of_birth,:with => DateRegex

new.html.erb / p>

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

(我知道这将允许一些假的出生日期,但我宁愿不安装任何类似的验证但是,在测试出生日期时,似乎没有在正则表达式中强制执行4-2-2。它允许2-2-2有时,2-4-2,2-2-4,它允许连字符和斜杠...帮助?



另外,如果有必要,我如何使用3个文本字段并让它进入一个mysql date_of_birth列?

解决方案

你可以随时使用 Date.parse 使您的生活更容易。如果可以解析,可能是有效的日期:

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

这样做的优点是可以拒绝99-99-99和2月30日的事情。


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.

这篇关于出生日期正则表达式yyyy-mm-dd for rails app的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆