简体   繁体   English

如何在Rails中为date_select设置今天的最长时间?

[英]How to set the max date of being today for date_select in Rails?

I have where a person can choose date of birth: 我在哪里可以选择出生日期:

= form.date_select :date_of_birth, start_year: Date.current.year, end_year: Date.current.year - 333

I want it to have the maximum date of today. 我希望它有今天的最大日期。 The max day must be equal to today and max month. 最长日期必须等于今天和最长月份。 Not only year. 不只是一年。

I've tried "min: Date.today" and "max: Date.today" and it didn't work out. 我已经尝试过“最小:Date.today”和“最大:Date.today”,但没有成功。

How can I do that? 我怎样才能做到这一点?

Ok, based on the negative points I got on my previous answer, let me explain this a bit more. 好吧,基于我先前回答的负面观点,让我再解释一下。 The Rails datepicker renders three selects, one for day, one for month and one for year. Rails日期选择器呈现三个选择,一个选择为日,一个选择为月,一个选择为年。 Since this is "fixed" there's no option to reduce the amount of days or months. 由于此问题是“固定的”,因此无法选择减少几天或几个月的时间。 This would not allow you to select a valid date anymore. 这将不再允许您选择有效日期。 The only thing you can change is the range of years. 您唯一可以更改的是年份范围。 You already did that in your sample code. 您已经在示例代码中做到了。

Now, back to your use case. 现在,回到您的用例。 You'd like to prevent someone inputing a date in the future? 您想阻止某人将来输入日期吗? Sure. 当然。 You've got three options: 您有三种选择:

  1. Only validate this server side, through a model validation and present the user back with the error message: "birth date should be in the past". 仅通过模型验证来验证此服务器端,并向用户显示错误消息:“出生日期应该在过去”。 Always do this!! 总是这样做!

The following are nice-to-haves to add to 1: 以下是要添加到1的最佳方法:

  1. Capture form submission through JS, check the submitted date and show error in case the date is invalid 通过JS捕获表单提交,检查提交日期并在日期无效的情况下显示错误
  2. Change the way you display the date through some kind of Datepicker plugin. 通过某种Datepicker插件更改显示日期的方式。 jQuery UI has a few nice one: https://jqueryui.com/datepicker/ . jQuery UI有一些不错的界面: https : //jqueryui.com/datepicker/ This one allows you to better configure allowed dates, since it is programmed client-side 由于它是在客户端编程的,因此您可以更好地配置允许的日期

Hope this helps. 希望这可以帮助。

Don't bother about dates in the future yet. 不要担心将来的日期。 Just ignore such bad entries for now. 现在暂时忽略此类不良条目。 Best to add a validation to the model that checks whether the submitted date < Date.today . 最好向模型添加验证,以检查提交的date < Date.today是否date < Date.today If you do wish to have front-end / client-side validation, look for a JS / jQuery datepicker. 如果您确实希望进行前端/客户端验证,请查找JS / jQuery datepicker。 These are more easy to configure and support direct inline error messages. 这些更易于配置并支持直接内联错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM