简体   繁体   English

如何在html中设置年份的最大值和最小值

[英]How to set the max and min value for year in html

I need to verify the max and min value from a date before submit a form.我需要在提交表单之前验证某个日期的最大值和最小值。 I want to send dates between 01-01-2005 and 12-12-2020.我想发送 01-01-2005 和 12-12-2020 之间的日期。 How can I do ti in php.我怎样才能在 php.ini 中做 ti。 If it's not possible in php, can be in javascript (jquery)如果在 php 中不可能,可以在 javascript (jquery)

<input type="date" name="datepost" value="<?php echo date('Y-m-d');"/>

Like I mentioned in the comments, all you really need to limit the range of inputs in a date-input element is the min and max attributes.就像我在评论中提到的那样,您真正需要限制 date-input 元素中的输入范围是minmax属性。 No JavaScript needed!不需要 JavaScript!

 <input type="date" name="datepost" min="2005-01-01" max="2020-12-12" value="<?php echo date('Ym-d'); ?>"/>

This will limit the date, allowing January 1st, 2005 to be the minimum date to be available for selection in the form, and December 12th, 2020 to be the maximum date available.这将限制日期,使 2005 年 1 月 1 日成为可在表格中选择的最短日期,而 2020 年 12 月 12 日成为最长可用日期。

Although, the user can specify the date by simply typing in a date of their choice (instead of selecting one with their cursor from the selection-window), outside of those parameters, so you should validate this in PHP (on a server-side level) too, which you should do in any case for all user-inputs.虽然用户可以通过简单地输入他们选择的日期(而不是从选择窗口中选择一个)来指定日期,但在这些参数之外,因此您应该在 PHP 中验证这一点(在服务器端级别)也是如此,无论如何您都应该对所有用户输入执行此操作。 You can also validate it in JavaScript, but always validate server-side.您也可以在 JavaScript 中对其进行验证,但始终在服务器端进行验证。 See the other answer for a way of validating it in PHP.有关在 PHP 中验证它的方法,请参阅其他答案。

This PHP method will check to see if the posted date is between the range defined.此 PHP 方法将检查发布日期是否在定义的范围内。

Post to this page to validate.发布到此页面以进行验证。

$user_time = date('Y-m-d', $_POST['datepost']);
$min = date('Y-m-d', strtotime('01-01-2005'));
$max = date('Y-m-d', strtotime('12-12-2020')); 

if (($user_time > $min) && ($user_time < $max)) {
    //Between Dates
}
else { 
 //Not between
}

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

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