【问题标题】:Date validation while typing in input field in Jquery在 Jquery 中输入输入字段时的日期验证
【发布时间】:2017-11-21 12:13:12
【问题描述】:

我有一个可以接受日期的输入文本字段。如果距离今天的日期不超过一个月,我需要验证日期。 例如用户不能在 2017 年 7 月 19 日之后进入。 如何验证此字段。

注意:它不是日期选择器字段。

我尝试了以下代码

if(new Date(jQuery('#inputDate').val()) > (new Date().getDate()+31)) {
                alert("you are not allowed to select after one month");
                jQuery('#inputDate').val('');}

【问题讨论】:

  • @Mathi 问题解决了吗?

标签: jquery validation date


【解决方案1】:

您可以创建您的自定义 AddDays 方法并在 if 条件下使用它,如下所示

Date.prototype.addDays = function(days) {
  var yourDate = new Date(this.valueOf());
  yourDate.setDate(yourDate.getDate() + days);
  return yourDate;
}

var yourDate= new Date();

$("#inputDate").on("change", function(e){
  // includes current day
  if(new Date($(this).val()) >= yourDate.addDays(30))
  {
      console.log("you are not allowed to select more than month");
      alert("you are not allowed to select more than month");
      $(this).val("");
  }
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="date" id="inputDate">

【讨论】:

  • 你应该在没有通过时清除输入字段,否则保留该值。你可以在你的函数中清除它而不是设置它。
  • @MilanChheda 感谢您提供信息,我已经更新了我的答案
  • 不错。您应该使用$(this) 而不是使用jQuery('#inputDate') 再次创建一个新的。
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多