javascript - 如何在jquery中测试用户给出的生日日期?

标签 javascript jquery html datepicker

我从 jquery-ui 添加了日期选择器。问题是,如果用户没有从日期选择器中选择日期,他也可以在日期字段中写入他的生日。现在,我希望,如果有人在日期字段中填写了错误的日期,该字段将自动变为空白,并给他一条消息,要求他填写有效的日期。我怎样才能做到这一点?

代码如下

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>

<link rel="stylesheet" href="css/jquery_ui.css">

<script src="js/jquery.js"></script>
<script src="js/jquery_ui.js"></script>
<script src="js/datepicker.js"></script>

</head>

<body>

<p>Date: <input type="text" id="datepicker" /></p>

</body>
</html>


//This is datepicker.js file

$( function() {
    $( "#datepicker" ).datepicker({
      changeMonth: true,
      changeYear: true,
      yearRange: "c-200:c+200",
      dateFormat: 'yy-mm-dd',
      maxDate: 0
    });
} );

最佳答案

您可以使用 JQuery 验证,请参阅以下内容:

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>

<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>

<body>
  <form id="myform">
    <p>Date: <input type="text" name="datepicker" id="datepicker" /></p>
    <input type="submit" />
  </form>
</body>
  <script>
    
$( function() {
    $( "#datepicker" ).datepicker({
      changeMonth: true,
      changeYear: true,
      yearRange: "c-200:c+200",
      dateFormat: 'yy-mm-dd',
      maxDate: 0
    });
} );
    
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});
    
$( "#myform" ).validate({
  rules: {
    datepicker: {
      required: true,
      date: true
    }
  }
})
  </script>
</html>

希望对你有帮助,再见。

关于javascript - 如何在jquery中测试用户给出的生日日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42339685/

相关文章:

javascript - AngularJS 应用程序 : unable to update $index

javascript - 显示/隐藏 HTML 元素 : better set Bootstrap 4's [hidden] attribute or call jQuery' s . hide() 函数?

从按钮到函数的 JavaScript 事件

javascript - jQuery 选择器不起作用?

javascript - onLoad 事件在图像完成加载之前触发

Html,正文 100% 高度和内容的动态宽度

javascript - Angular UI Router 嵌套 View 问题

javascript - 为什么我的 js.d3 代码不显示轴?

php - php 是否在 'html body' 之前加载?

php - 使用 EOF 的缺点?