Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date input type validation in javascript?

I can't quite figure out how to validate a date input type in javascript. I tried looking on the internet but I just couldnt find anything.

I have one field that ask the user to input its birthday. I want to validate it in javascript with the certain limits on days months and, especially years. For example if the user input more than 2016(or the current year) it would give an error. I can't quite figure out how to "extract" the date input type and control every elements of it (day, month, year).

Here part of my html

<form method="POST" action="request.jsp" onsubmit="return validate()">
Date of birth: <input type="date" id="bday" name="bday" value="">
</form>

Javascript:

var birthday = document.getElementById('bday').value;

This is all i've got.. please help?

like image 953
shean Avatar asked Dec 24 '22 08:12

shean


2 Answers

TLDR

You have to parse the string as a date (JavaScript provides the Date API for this very use case).

Full answer

You're on the right track. Here's a JSBin example I did. Try opening the console and changing the date, and you'll see it logged.

$('#birthday').on('change', function() {
   console.log(new Date(this.value));
});

(I'm using jQuery in the above example just for convenience sake, but you can use whatever you want.)

The problem you have here is that the date is logged as a string. You can use the JavaScript Date object to parse the string.

Based on whatever validation you want to do, you can use various date object methods (like getFullYear, for example) and match those against the input.

I'll leave the full implementation up to you, but the inside of the change handler might look like:

var date = new Date(this.value);

if(date.getFullYear() > 2016) {
  // do something (like show a message, for example)
}
like image 191
Josh Beam Avatar answered Jan 06 '23 22:01

Josh Beam


If you are able to get the value of the input element with:

 var birthday = document.getElementById('bday').value;

Then birthday will be available to you as a string (all input values are always returned to JavaScript as strings). From there, you'd need to convert that string to a date with:

 var dob = Date.parse(birthday);

Then, once you've got the entire date, you can extract the pieces of it with the various JavaScript Date/Time methods:

 var month = dob.getMonth(); // months start counting from zero!
 var day   = dob.getDate();
 var year  = dob.getFullYear();  // getYear() provides 3 digit year!

Here's a working example:

var birthday = null, btn = null, output = null;

// Wait until the document is ready for interaction:
window.addEventListener("DOMContentLoaded", function(){

     // Get references to DOM elements needed:
     birthday = document.getElementById('bDate');
     btn = document.getElementById('btnGetDate');
     output = document.getElementById('result');


     // Set up an event callback for when the button gets clicked:      
     btn.addEventListener("click", function(){
       

        // Create a new Date that converts the input date
        var dob =new Date(birthday.value);
        alert(dob);

        // Extract pieces of the date:
        var month = dob.getMonth(); // months start counting from zero!
        var day   = dob.getDate();  
        var year  = dob.getFullYear();

        // Now that you have the pieces of the date, you can validate as you wish:
        // e.g. if(year > 2016) { . . . }
  
        // Write out date:
        output.innerHTML = ++month + "/" + ++day + "/" + year; 

     });
  
});





  
<input type="date" id="bDate">
<input type="button" id="btnGetDate" value="Get Date">
<p id="result"></p>

NOTE: Keep in mind that Daylight Savings Time will have an effect on the result depending on what time of day it is. See: How to check if the DST (Daylight Saving Time) is in effect and if it is what's the offset? for more info. on that.

like image 36
Scott Marcus Avatar answered Jan 06 '23 22:01

Scott Marcus