1

I've added datepicker from jquery-ui. The problem is, if a user doesn't select a date from the datepicker, he can also write his birthdate in the date field. Now, I want, if someone fill up the date field with a wrong date, the field will automatically become blank and give him a message to write a valid date. How can I do that?

The codes are given below

<!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
    });
} );

1 Answers1

0

You could use JQuery Validation, see following:

<!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>

I hope it helps you, bye.

Alessandro
  • 4,382
  • 8
  • 36
  • 70
  • But the problem is, this code does not detect 31 February, 31 November as invalid dates. An user will get a tick mark if he writes 2017-02-31 as his birth-date. – Nahid Sultan Feb 20 '17 at 09:14