简体   繁体   English

HTML5 输入类型日期验证-如何限制输入

[英]HTML5 Input type date validation - how to restrict the entry

hey guys can someone help me out with this.嘿伙计们可以帮我解决这个问题。 I am using the HTML5 input type = date in one of my client side input forms.我在我的客户端输入 forms 之一中使用 HTML5 输入类型 = 日期。 I want the user to be able to add a date only for the month.我希望用户只能为该月添加一个日期。 So if the date is 1st June then upto 30th June and if the date is 10th June then also only till 30th June.因此,如果日期是 6 月 1 日,那么直到 6 月 30 日,如果日期是 6 月 10 日,那么也只能到 6 月 30 日。 Is there a way I can achieve this in the front end.有没有办法可以在前端实现这一点。

One possible solution or maybe more of a workaround is to take the date and then compare it in my app.js with the the current month and send the user to an error page if the month is not matching with the current month.一种可能的解决方案或更多的解决方法是获取日期,然后在我的 app.js 中将其与当前月份进行比较,如果月份与当前月份不匹配,则将用户发送到错误页面。 But I was hoping I can validate this somehow in the front end.但我希望我能在前端以某种方式验证这一点。

I read about the min and max parameter but doesn't look like a viable solution for a monthly validation, unless I am missing something我阅读了有关 min 和 max 参数的信息,但看起来不像是每月验证的可行解决方案,除非我遗漏了什么

Can some one help?有人可以帮忙吗?

Regards, Sandeep问候,桑迪普

Min and max can be used with dates.最小值和最大值可以与日期一起使用。 See: Constraint Validation at MDN.请参阅:MDN 的约束验证

 let today = new Date(); let maxDate = new Date(); maxDate.setUTCDate(1); maxDate.setUTCMonth(maxDate.getUTCMonth()+1); maxDate.setUTCDate(0); document.getElementById('thedate').setAttribute('max', `${maxDate.getUTCFullYear()}-${(maxDate.getUTCMonth()+1).toString().padStart(2,'0')}-${maxDate.getUTCDate()}`); document.getElementById('thedate').setAttribute('min', `${today.getUTCFullYear()}-${(today.getUTCMonth()+1).toString().padStart(2,'0')}-${today.getUTCDate()}`); console.log(document.getElementById('thedate')) document.forms[0].onsubmit = function(e) { e.preventDefault(); console.log(`the form is ${e.target.reportValidity()?'':'not '}valid`); return false; }
 <form> <input id="thedate" type="date"> <input type="submit"> </form>

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

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