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?
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)
}
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.
Input type date is not supported in all browsers, so you should detect that and replace the input with a suitable alternative that includes the format that is required.
Where supported, the input will return an ISO 8601 format date string without a time zone. According to ISO 8601, this should be treated as local, but TC39 in their wisdom decided that it should be treated as UTC, so that is what Date.parse (and the Date constructor) will do in most cases. In some it will be treated as local and in IE 8 as invalid. So for systems with a timezone that is west of Greenwich, Date.parse('2016-03-20') will return a Date object that, when displayed as a local date, will be '2016-03-19', i.e. one day early.
So you should manually parse the date string, validate the date using one of the many answers here, then check whether the year, month and day are within your constraints.
if you're simply trying to validate whether or not a string is a valid date, you can just check that it creates a valid date object.
function isValidDate(d){
return !isNaN((new Date(d)).getTime());
}
https://jsfiddle.net/46cztok6/
so your validate() function would look like this.
function validate(){
var birthday = document.getElementById('bday').value;
if(!isValidDate(birthday)){
alert("you did not enter a valid birthday");
return false;
}
}
Here is a bin so you can have an idea how to start validating this type of field: https://jsbin.com/lifacaxonu/edit?html,js,console,output
$('#birthday').on('change', function() {
var val = this.value.split('-');
if (val[0] > new Date().getFullYear()) {
console.log('invalid')
} else {
console.log('ok')
}
});
After looking out for 3 hours, i wrote this and achieved dd/mm/yyyy date input using plain Javascript.
<div class="container">
<div class="datetime-container">
<input type="text" placeholder="write your date" id="datetime" onblur="validateDate()">
<p id="error"></p><br>
<input type="tel" maxlength="10" placeholder="dd/mm/yyyy"
oninput="this.value = DDMMYYYY(this.value, event)" />
</div>
</div>
<script>
function DDMMYYYY(value, event) {
let newValue = value.replace(/[^0-9]/g, '').replace(/(\..*)\./g, '$1');
const dayOrMonth = (index) => index % 2 === 1 && index < 4;
// on delete key.
if (!event.data) {
return value;
}
let currentYear = new Date().getFullYear();
console.log(newValue.slice(2,4));
if(newValue.length>=2 && newValue.slice(0,2)>31){
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(0,2),31);
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid day!";
}else if(newValue.length>=4 &&newValue.slice(2,4)>12){
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid month!";
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(2,4),12);
}else if(newValue.length==8 && newValue.slice(4)>currentYear){
tempValue = newValue;
newValue = tempValue.replace(tempValue.slice(4),currentYear);
document.getElementById("error").style.display = "initial";
document.getElementById("error").innerHTML = "Invalid year!";
}
else{
document.getElementById("error").style.display="none";
}
return newValue.split('').map((v, i) => dayOrMonth(i) ? v + '/' : v).join('');;
}
</script>
Date format is in "mm/dd/yyyy". It is not giving me proper result. It is only validating month.
<input type="text" name="durationstart" id="durationstart" value="">
<input type="text" name="durationend" id="durationend" value="" onclick="return chk_val12()" >
<script>
function chk_val12()
{
var durationstart = document.getElementById('durationstart').value;
var durationend = document.getElementById('durationend').value;
if(durationstart>durationend)
{
alert("Please enter proper duration range");
return false;
}
else
{
return true;
}
}
</script>
You cannot compare validate date like this.
Text box contains the value of string dataType. So what the below code does is
if(durationstart>durationend) // Invalid
Instead parse it to date object.
Updates:
Though it works, there are chances for browser compatibility so here I have written the full date parsing
function chk_val12() {
var durationstart = document.getElementById('durationstart').value;
var durationend = document.getElementById('durationend').value;
var st = durationstart.split("/");
var en = durationend.split("/");
var startDate = new Date(st[2], (+st[0] - 1), st[1]);
var endDate = new Date(en[2], (+en[0] - 1), en[1]);
if (startDate > endDate) {
alert("Please enter proper duration range");
return false;
} else {
return true;
}
}
JSFiddle
FYI: Make sure user enters the right date format.
What it does?
1) Split the dateString you have like
var st = durationstart.split("/");
2) Parse it like new Date(YYYY, MM, DD)
var startDate = new Date(st[2], (+st[0] - 1), st[1]);
Extracting and comparing formatted date strings from text inputs
You'll need to use the Date object's parse method to convert the input strings into milliseconds, then compare the 2:
var durationstart = Date.parse( document.getElementById('durationstart').value );
var durationend = Date.parse( document.getElementById('durationend').value );
This depends upon the input being entered in a way the Date.parse method expects though — in formats following either the Wed, 3 Feb 2014 or 2014-02-03 standards.
Converting arbitrary formats into date objects
If the user is likely to use another input format, you may want to use a plugin such as Sugar to parse a wider range of possible formats. Sugar adds a Date.create( inputString ) method which accepts the following formats.
Using HTML5 #type=date inputs
An alternative for modern browsers is to use inputs of type date instead of text, which would allow you to extract the date values directly without fear of the user entering an unparseable format. Using this method you would change the HTML to:
<input type="date" name="durationstart" id="durationstart" value="">
<input type="date" name="durationend" id="durationend" value="" onclick="return chk_val12()" >
…and use the native valueAsDate method to extract the values as follows:
var durationstart = document.getElementById('durationstart').valueAsDate;
var durationend = document.getElementById('durationend').valueAsDate;
Try this
function dateCheck() {
fDate = Date.parse(document.getElementById("durationstart").value);
lDate = Date.parse(document.getElementById("durationend").value);
if(fDate >lDate )
{
alert("Please enter proper duration range");
return false;
}
else
{
return true;
}
}
I wish to check whether a one given date is less than the other date using JavaScript + jQuery.
However, when checking a date that is one day less than the given date, the condition is not met.
This is my code;
$('#payment_date').change(function(){
payment_date_1 = String($("#payment_date").val());
s_date_1 = String($("#s_date").text());
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date<s_date){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
ex: when s_date == '2013-07-02' and payment_date == '2013-07-01' the condition is returning false rather than true.
My HTML:
<span style="display:none;" id="s_date">2013-07-02</span>
<input type="text" value="" name="payment_data_info[payment_date]" id="payment_date" class="hasDatepicker" readonly="readonly">
Note; I have checked if both dates are valid, two dates are returning valid dates and the condition is working perfectly well for other instances
I just found out why; I'm using jQuery's date picker. Dates less than and equal to 2013-07-10 returns a valid date and dates less than 2013-07-10 and larger than 2013-06-30 returns an invalid date. Any idea why?
First of all check if variable declaration is the problem, than check if the string parsing returns the dates you're expecting. Maybe s_date and payment_date are invalid after all?
I expierenced difficulties too with the direct comparison (don't know why), so I used the valueOf-function to get values for comparison.
Sure it works ;)
http://jsfiddle.net/4MQkK/
payment_date_1 = "2013-07-01";
s_date_1 = "2013-07-02";
payment_date = new Date(payment_date_1);
s_date = new Date(s_date_1);
if(payment_date < s_date){
alert(payment_date + "is lower than " + s_date);
}
Check your values of payment_date_1 and s_date_1 at least one of them could not be parsed correctly
Try this , I hope it will help.
$('#payment_date').change(function(){
var payment_date_1 = $("#payment_date").val(); //add var
var s_date_1 = $("#s_date").text(); //add var
var payment_date = new Date(payment_date_1);
var s_date = new Date(s_date_1);
if((payment_date.valueOf())<(s_date.valueOf())){
alert("please enter a correct date");
$("#payment_date").val("");
}
});
2 Possible Causes:
1) Where Date is called as a constructor with more than one argument,
if values are greater than their logical range (e.g. 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. E.g. new Date(2013,13,1) is equivalent to new Date(2014,1,1),
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
your date format is 'dd/MM/yyyy' but new Date () use format yyyy/dd/mm so 2013-06-30: 30 is month i.e. 30 month more then 06/01/2013 --> 06/06/2015
you need to change the format. for example:
var myDate = "2013/01/30"
var split= myDate .split("/");
new Date (split[2],split[1],split[0]);
2) months in Date() in javascript they numeric 0-11. so 01/03/2013 changed to 01/04/2013
int month = myMonth -1; // for example: mymonth = 'March' => month = 2
can use new Date(2013,month,30);
You can do something like this.
var payment_date_1 = $("#payment_date").val();
var s_date_1 = $("#s_date").text(); or $("#s_date").val();
// IF s_date_1 is a input field then you have to use .val()
For typecast String. You can do
var payment_date_1 = $("#payment_date").val().toString();
var s_date_1 = $("#s_date").val().toString();
PLease create date objects and then check
var first = new Date($("#s_date").text());
var second = new Date($("#s_date_1").text());
if(first.getTime() < second.getTime()) {
// code
}
I'd like to tell the difference between valid and invalid date objects in JS, but couldn't figure out how:
var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
Any ideas for writing an isValidDate function?
Ash recommended Date.parse for parsing date strings, which gives an authoritative way to check if the date string is valid.
What I would prefer, if possible, is have my API accept a Date instance and to be able to check/assert whether it's valid or not. Borgar's solution does that, but I need to test it across browsers. I also wonder whether there's a more elegant way.
Ash made me consider not having my API accept Date instances at all, this would be easiest to validate.
Borgar suggested testing for a Date instance, and then testing for the Date's time value. If the date is invalid, the time value is NaN. I checked with ECMA-262 and this behavior is in the standard, which is exactly what I'm looking for.
Here's how I would do it:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d)) { // d.getTime() or d.valueOf() will also work
// date object is not valid
} else {
// date object is valid
}
} else {
// not a date object
}
Update [2018-05-31]: If you are not concerned with Date objects from other JS contexts (external windows, frames, or iframes), this simpler form may be preferred:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
Update [2021-02-01]: Please note that there is a fundamental difference between "invalid dates" (2013-13-32) and "invalid date objects" (new Date('foo')). This answer does not deal with validating date input, only if a Date instance is valid.
Instead of using new Date() you should use:
var timestamp = Date.parse('foo');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
}
Date.parse() returns a timestamp, an integer representing the number of milliseconds since 01/Jan/1970. It will return NaN if it cannot parse the supplied date string.
You can check the validity of a Date object d via
d instanceof Date && isFinite(d)
To avoid cross-frame issues, one could replace the instanceof check with
Object.prototype.toString.call(d) === '[object Date]'
A call to getTime() as in Borgar's answer is unnecessary as isNaN() and isFinite() both implicitly convert to number.
shortest answer to check valid date
if(!isNaN(date.getTime()))
My solution is for simply checking whether you get a valid date object:
Implementation
Date.prototype.isValid = function () {
// An invalid date object returns NaN for getTime() and NaN is the only
// object not strictly equal to itself.
return this.getTime() === this.getTime();
};
Usage
var d = new Date("lol");
console.log(d.isValid()); // false
d = new Date("2012/09/11");
console.log(d.isValid()); // true
I have seen some answers that came real close to this little snippet.
JavaScript way:
function isValidDate(dateObject){
return new Date(dateObject).toString() !== 'Invalid Date';
}
console.log(isValidDate('WTH')); // -> false
console.log(isValidDate(new Date('WTH'))); // -> false
console.log(isValidDate(new Date())); // -> true
ES2015 way:
const isValidDate = dateObject => new Date(dateObject)
.toString() !== 'Invalid Date';
console.log(isValidDate('WTH')); // -> false
console.log(isValidDate(new Date('WTH'))); // -> false
console.log(isValidDate(new Date())); // -> true
You can simply use moment.js
Here is an example:
var m = moment('2015-11-32', 'YYYY-MM-DD');
m.isValid(); // false
The validation section in the documentation is quite clear.
And also, the following parsing flags result in an invalid date:
overflow: An overflow of a date field, such as a 13th month, a 32nd day of the month (or a 29th of February on non-leap years), a 367th day of the year, etc. overflow contains the index of the invalid unit to match #invalidAt (see below); -1 means no overflow.
invalidMonth: An invalid month name, such as moment('Marbruary', 'MMMM');. Contains the invalid month string itself, or else null.
empty: An input string that contains nothing parsable, such as moment('this is nonsense');. Boolean.
Etc.
Source: http://momentjs.com/docs/
Would like to mention that the jQuery UI DatePicker widget has a very good date validator utility method that checks for format and validity (e.g., no 01/33/2013 dates allowed).
Even if you don't want to use the datepicker widget on your page as a UI element, you can always add its .js library to your page and then call the validator method, passing the value you want to validate into it. To make life even easier, it takes a string as input, not a JavaScript Date object.
See: http://api.jqueryui.com/datepicker/
It's not listed as a method, but it is there-- as a utility function. Search the page for "parsedate" and you'll find:
$.datepicker.parseDate( format, value, settings ) - Extract a date from a string value with a specified format.
Example usage:
var stringval = '01/03/2012';
var testdate;
try {
testdate = $.datepicker.parseDate('mm/dd/yy', stringval);
// Notice 'yy' indicates a 4-digit year value
} catch (e)
{
alert(stringval + ' is not valid. Format must be MM/DD/YYYY ' +
'and the date value must be valid for the calendar.';
}
(More info re specifying date formats is found at http://api.jqueryui.com/datepicker/#utility-parseDate)
In the above example, you wouldn't see the alert message since '01/03/2012' is a calendar-valid date in the specified format. However if you made 'stringval' equal to '13/04/2013', for example, you would get the alert message, since the value '13/04/2013' is not calendar-valid.
If a passed-in string value is successfully parsed, the value of 'testdate' would be a Javascript Date object representing the passed-in string value. If not, it'd be undefined.
After reading every answer so far, I am going to offer the most simple of answers.
Every solution here mentions calling date.getTime(). However, this is not needed, as the default conversion from Date to Number is to use the getTime() value. Yep, your type checking will complain. :) And the OP cleary knows they have a Date object, so no need to test for that either.
To test for an invalid date:
isNaN(date)
To test for a valid date:
!isNaN(date)
or (thanks to icc97 for this alternative)
isFinite(date)
or typescript (thanks to pat-migliaccio)
isFinite(+date)
// check whether date is valid
var t = new Date('2011-07-07T11:20:00.000+00:00x');
valid = !isNaN(t.valueOf());
I really liked Christoph's approach (but didn't have enough of a reputation to vote it up).
For my use, I know I will always have a Date object so I just extended date with a valid() method.
Date.prototype.valid = function() {
return isFinite(this);
}
Now I can just write this and it's much more descriptive than just checking isFinite in code...
d = new Date(userDate);
if (d.valid()) { /* do stuff */ }
I use the following code to validate values for year, month and date.
function createDate(year, month, _date) {
var d = new Date(year, month, _date);
if (d.getFullYear() != year
|| d.getMonth() != month
|| d.getDate() != _date) {
throw "invalid date";
}
return d;
}
For details, refer to Check date in javascript
you can check the valid format of txDate.value with this scirpt. if it was in incorrect format the Date obejct not instanced and return null to dt .
var dt = new Date(txtDate.value)
if (isNaN(dt))
And as #MiF's suggested in short way
if(isNaN(new Date(...)))
Too many complicated answers here already, but a simple line is sufficient (ES5):
Date.prototype.isValid = function (d) { return !isNaN(Date.parse(d)) } ;
or even in ES6 :
Date.prototype.isValid = d => !isNaN(Date.parse(d));
Why am I writing a 48th answer after so many have tried before me? Most of the answers are partly correct and will not work in every situation, while others are unnecessarily verbose and complex. Below is a very concise solution. This will checking if it is Date type and then check if a valid date object:
return x instanceof Date && !!x.getDate();
Now for parsing date Text: Most of the solutions use Date.parse(), or "new Date()" -- both of these will fail certain situations and can be dangerous. JavaScript parses a wide variety of formats and also is dependent on localization. For example, strings like "1" and "blah-123" will parse as a valid date.
Then there are posts that either use a ton of code, or a mile-long RegEx, or use third party frameworks.
This is dead simple method to validate a date string.
function isDate(txt) {
var matches = txt.match(/^\d?\d\/(\d?\d)\/\d{4}$/); //Note: "Day" in the RegEx is parenthesized
return !!matches && !!Date.parse(txt) && new Date(txt).getDate()==matches[1];
}
TEST THE FUNCTION
<br /><br />
<input id="dt" value = "12/21/2020">
<input type="button" value="validate" id="btnAction" onclick="document.getElementById('rslt').innerText = isDate(document.getElementById('dt').value)">
<br /><br />
Result: <span id="rslt"></span>
The first line of isDate parses the input text with a simple RegEx to validate for date formats mm/dd/yyyy, or m/d/yyyy. For other formats, you will need to change the RegEx accordingly, e.g. for dd-mm-yyyy the RegEx becomes /^(\d?\d)-\d?\d-\d{4}$/
If parse fails, "matches" is null, otherwise it stores the day-of-month. The second lines does more tests to ensure it is valid date and eliminates cases like 9/31/2021 (which JavaScript permits). Finally note the double-whack (!!) converts "falsy" to a boolean false.
This just worked for me
new Date('foo') == 'Invalid Date'; //is true
However this didn't work
new Date('foo') === 'Invalid Date'; //is false
None of these answers worked for me (tested in Safari 6.0) when trying to validate a date such as 2/31/2012, however, they work fine when trying any date greater than 31.
So I had to brute force a little. Assuming the date is in the format mm/dd/yyyy. I am using #broox answer:
Date.prototype.valid = function() {
return isFinite(this);
}
function validStringDate(value){
var d = new Date(value);
return d.valid() && value.split('/')[0] == (d.getMonth()+1);
}
validStringDate("2/29/2012"); // true (leap year)
validStringDate("2/29/2013"); // false
validStringDate("2/30/2012"); // false
For Angular.js projects you can use:
angular.isDate(myDate);
I wrote the following solution based on Borgar's solution. Included in my library of auxiliary functions, now it looks like this:
Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.prototype.toString.call(obj) === '[object Date]';
}
Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.isDate(obj) && !isNaN(obj.getTime());
}
I rarely recommend libraries when one can do without. But considering the plethora of answers so far it seems worth pointing out that the popular library "date-fns" has a function isValid. The following documentation is taken from their website:
isValid argument
Before v2.0.0
v2.0.0 onward
new Date()
true
true
new Date('2016-01-01')
true
true
new Date('')
false
false
new Date(1488370835081)
true
true
new Date(NaN)
false
false
'2016-01-01'
TypeError
false
''
TypeError
false
1488370835081
TypeError
true
NaN
TypeError
false
Date.prototype.toISOString throws RangeError (at least in Chromium and Firefox) on invalid dates. You can use it as a means of validation and may not need isValidDate as such (EAFP). Otherwise it's:
function isValidDate(d)
{
try
{
d.toISOString();
return true;
}
catch(ex)
{
return false;
}
}
IsValidDate: function(date) {
var regex = /\d{1,2}\/\d{1,2}\/\d{4}/;
if (!regex.test(date)) return false;
var day = Number(date.split("/")[1]);
date = new Date(date);
if (date && date.getDate() != day) return false;
return true;
}
I've written this function. Pass it a string parameter and it will determine whether it's a valid date or not based on this format "dd/MM/yyyy".
here is a test
input: "hahaha",output: false.
input: "29/2/2000",output: true.
input: "29/2/2001",output: false.
function isValidDate(str) {
var parts = str.split('/');
if (parts.length < 3)
return false;
else {
var day = parseInt(parts[0]);
var month = parseInt(parts[1]);
var year = parseInt(parts[2]);
if (isNaN(day) || isNaN(month) || isNaN(year)) {
return false;
}
if (day < 1 || year < 1)
return false;
if(month>12||month<1)
return false;
if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 31)
return false;
if ((month == 4 || month == 6 || month == 9 || month == 11 ) && day > 30)
return false;
if (month == 2) {
if (((year % 4) == 0 && (year % 100) != 0) || ((year % 400) == 0 && (year % 100) == 0)) {
if (day > 29)
return false;
} else {
if (day > 28)
return false;
}
}
return true;
}
}
None of the above solutions worked for me what did work however is
function validDate (d) {
var date = new Date(d);
var day = "" + date.getDate();
if ( day.length == 1 ) day = "0" + day;
var month = "" + (date.getMonth() + 1);
if ( month.length == 1 ) month = "0" + month;
var year = "" + date.getFullYear();
return (( month + "/" + day + "/" + year ) == d );
}
the code above will see when JS makes 02/31/2012 into 03/02/2012 that it's not valid
Date object to string is more simple and reliable way to detect if both fields are valid date.
e.g. If you enter this "-------" to the date input field. Some of the above answers won't work.
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
var startDate = new Date($(params).val());
var endDate = new Date(value);
if(startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {
return false;
} else {
return endDate > startDate;
}
},'Must be greater than {0}.');
you can convert your date and time to milliseconds getTime()
this getTime() Method return Not a Number NaN when not valid
if(!isNaN(new Date("2012/25/255").getTime()))
return 'valid date time';
return 'Not a valid date time';
I combined the best performance results I found around that check if a given object:
is a Date instance (benchmark here)
has a valid date (benchmark here)
The result is the following:
function isValidDate(input) {
if(!(input && input.getTimezoneOffset && input.setUTCFullYear))
return false;
var time = input.getTime();
return time === time;
};
A ready function based on top rated answer:
/**
* Check if date exists and is valid.
*
* #param {String} dateString Date in YYYY-mm-dd format.
*/
function isValidDate(dateString) {
var isValid = false;
var date;
date =
new Date(
dateString);
if (
Object.prototype.toString.call(
date) === "[object Date]") {
if (isNaN(date.getTime())) {
// Date is unreal.
} else {
// Date is real if month and day match each other in date and string (otherwise may be shifted):
isValid =
date.getUTCMonth() + 1 === dateString.split("-")[1] * 1 &&
date.getUTCDate() === dateString.split("-")[2] * 1;
}
} else {
// It's not a date.
}
return isValid;
}
No one has mentioned it yet, so Symbols would also be a way to go:
Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date") // true
Symbol.for(new Date()) === Symbol.for("Invalid Date") // false
console.log('Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date")', Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date")) // true
console.log('Symbol.for(new Date()) === Symbol.for("Invalid Date")', Symbol.for(new Date()) === Symbol.for("Invalid Date")) // false
Be aware of:
https://caniuse.com/#search=Symbol
Inspired by Borgar's approach I made sure that the code not only validates the date, but actually makes sure the date is a real date, meaning that dates like 31/09/2011 and 29/02/2011 are not allowed.
function(dateStr) {
s = dateStr.split('/');
d = new Date(+s[2], s[1] - 1, +s[0]);
if (Object.prototype.toString.call(d) === "[object Date]") {
if (!isNaN(d.getTime()) && d.getDate() == s[0] &&
d.getMonth() == (s[1] - 1)) {
return true;
}
}
return "Invalid date!";
}