1

I am writing an html file to take date input. I am using date picker to select the date, instead of selecting date from the date picker, if the user is manually typing the date in text field for ex: 09/31/16 I need to give information to the user that date is invalid date. But my code given below is taking as october 1st 2016 when I created the date object. if I am converting date to ISOString it is displaying as 30th sept. But my desired output is to display the message to the browser as an "Invalid date". Please help me as I have to resolve this because I am going to use dates at many places during my development. Thank You.

<html lang="en">
    <head>
        <meta charset="utf-8">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
        <script>
            $(function () {
                $("#datepicker").datepicker();
            });
            function verifyDate() {
                var d = new Date($("#datepicker").val());
                console.log(d);
                var d = new Date($("#datepicker").val()).toISOString();
                console.log(d);
            }
        </script>
    </head>
    <body>
        <p>Date: <input type="text" id="datepicker" onblur="verifyDate()"></p>
    </body>
</html>
Siva.G ツ
  • 831
  • 1
  • 7
  • 20
rajani chowdhary
  • 175
  • 1
  • 4
  • 16

2 Answers2

0

if you want to get the date on user selection, your code should be like:

<html lang="en">
<head>
 <meta charset="utf-8">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
    <script>
      $(function() {

      $("#datepicker").datepicker({
             onSelect: function(){ 
               var dateValue = $(this).datepicker('getDate'); 
             console.log(dateValue);
        }
       });  

     });       
    </script>    
    </head>
    <body>    
 <p>Date: <input type="text" id="datepicker" ></p>  

</body>
aitnasser
  • 1,216
  • 1
  • 9
  • 23
0

Following way of validating dates can help in this:

let dateObj = document.getElementById("datepicker");
if (dateObj.validity.badInput) {
   // show error message
}
Madhur Trivedi
  • 33
  • 1
  • 1
  • 8