Javascript date validator for multiple date patterns - javascript

With help from stackoverflow I made a .js file with two methods that check if the date entered is valid. It is working fine, but only if the date is entered with dashes - 12/12/2019. What approach can I take in my isValidDate method to make it work with multiple date patterns like - 12.12.2020 12-12-2020 etc. The only idea I have is to check somehow first what is the pattern and then create a separate case to split the date string by different characters, but it will look pretty ugly.
function isValidDate(dateString) {
var validDate = true;
// First check for the pattern
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
return false;
}
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[0], 10);
var month = parseInt(parts[1], 10);
var year = parseInt(parts[2], 10);
if(isNaN(day) || isNaN(month) || isNaN(year)){
return false;
}
// Check the ranges of month and year
if (year < 1000 || year > 3000 || month < 1 || month > 12) {
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Adjust for leap years
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
monthLength[1] = 29;
}
// Check the range of the day
if (!(day > 0 && day <= monthLength[month - 1])) {
return false;
}
return true;
};
/**
* Function which executes each time the input loses focus (onblur)
*/
function validateDate() {
// Get a reference to the container
var container = document.querySelector('.date');
// Clear stale error/success messages
container.className = container.className.replace('success', '');
container.className = container.className.replace('error', '');
// Get current value of input
var dateString = document.getElementById("Start-date").value;
// Test if the string is a valid date
var isValid = isValidDate(dateString);
// Update classess of container to show success/error
if (!isValid) {
container.className += ' error';
} else {
container.className += ' success';
}
}
I am calling the validateDate() function first

Please note I have not tested the regular expressions this is just an example of how to attack the probelm
// First check for the pattern var = dateChar
if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
dateChar = '/';
}
if (!/^\d{1,2}\-\d{1,2}\-\d{4}$/.test(dateString)) {
dateChar = '-';
}
if (!dateChar) {
return false;
}
var parts = dateString.split(dateChar);
....

Related

validate a date in dd/mm/yyyy format

I am trying to validate a date with regex but its failing, i am trying to use it to write it in input manually or select from a calendar on the side
<input type="text" name="FromDate" value="28/8/2022" id="Strtcalfield1" REQUIRED="yes" VALIDATE="date" MESSAGE="Please enter date (dd/MM/yyyy)." pattern="/^(\s{0,})(\d{2}\/\d{2}\/\d{4})(,\d{2}\/\d{2}\/\d{4}){1,}(\s){0,}$" oninvalid="this.setCustomValidity('Please enter date (dd/mm/yyyy).')" oninput="this.setCustomValidity('')"/>
and that is throwing an error
value is coming from backend, but when i choose rom calendar, it keeps on giving me an error
please enter date as dd/mm/yyyy as i see the date is correctly entered
You could validate the string with a JavaScript function instead of the regex pattern to ensure that it is a valid date. The following function parses the dd/mm/yyyy string pattern and ensures the day part is in the correct range for the parsed month and year values.
function validateDateString(dateString) {
// regex for date string format: dd/mm/yyyy
const dateFormatRegex = /^(0?[1-9]|[1-2][0-9]|3[01])[\/](0?[1-9]|1[0-2])[\/]\d{4}$/;
let isValidDate = false;
if (dateString.match(dateFormatRegex)) {
const dateParts = dateString.split('/');
if (dateParts.length == 3) {
const day = parseInt(dateParts[0]);
const month = parseInt(dateParts[1]);
const year = parseInt(dateParts[2]);
// valid month range is 1 - 12
if (month < 1 || month > 12) {
return false;
}
// validate days in month
const daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthLength = daysInMonth[month-1];
if ((month == 2) && ((!(year%4) && year%100) || !(year%400))) {
monthLength = 29;
}
if (day < 1 || day > monthLength) {
return false;
}
// checks have passed
isValidDate = true;
}
}
return isValidDate;
}
EDIT: The following modifications will allow the code to handle the date format of the locale used in the browser.
The getLocaleDateFormat function determines the locale date format by generating a unique date and identifying the position of each element in the locale string. The date separator character is also identified and the information is returned in a single object with keys: day, month, year and sep.
function getLocaleDateFormat() {
const dummyDate = new Date(1999,11,30).toLocaleDateString().replace(/1999/,"yyyy").replace(/30/,"dd").replace(/12/,"mm");
const findDateSegmentIndex = (pos) => {
let index = -1;
if (pos == 0) {
index = 0;
}
else if ((pos > 0) & (pos < 6)) {
index = 1;
}
else if ((pos > 5) & (pos < 10)) {
index = 2;
}
return index;
};
const localeInfo = {
"day": findDateSegmentIndex(dummyDate.search("dd")),
"month": findDateSegmentIndex(dummyDate.search("mm")),
"year": findDateSegmentIndex(dummyDate.search("yyyy")),
"sep": dummyDate[dummyDate.search(/\W/)]
};
return localeInfo;
}
The getDateStringFormat function uses the information in the object returned by getLocaleDateFormat() to assemble a string to create the regular expression which will match the locale date format. The object returned by the function includes the regular expression string in the regex key.
function getDateStringFormat() {
const dateLocale = getLocaleDateFormat();
const regexStringsObject = {
"day": '(0?[1-9]|[1-2][0-9]|3[01])',
"month": '(0?[1-9]|1[0-2])',
"year": '\\d{4}'
}
let regexElements = ['', '', ''];
regexElements[ dateLocale["day"] ] = regexStringsObject["day"];
regexElements[ dateLocale["month"] ] = regexStringsObject["month"];
regexElements[ dateLocale["year"] ] = regexStringsObject["year"];
const dateStringFormat = { ...dateLocale,
"regex": `^${regexElements[0]}[.\\-\\/]${regexElements[1]}[.\\-\\/]${regexElements[2]}$`
};
return dateStringFormat;
}
The updated validateDateString function uses the regex string in the object returned by getDateStringFormat() to parse the provided dateString. There are three different separators (-, ., /) handled. The locale date format information as determined in the getLocaleDateFormat function is used to validate the respective part of the date string.
function validateDateString(dateString) {
const dateFormat = getDateStringFormat();
let result = false;
const regex = new RegExp(dateFormat.regex);
if (dateString.match(regex)) {
const dateParts = dateString.split(/[.\-\/]/);
if (dateParts.length == 3) {
const day = parseInt(dateParts[dateFormat.day]);
const month = parseInt(dateParts[dateFormat.month]);
const year = parseInt(dateParts[dateFormat.year]);
// valid month range is 1 - 12
if (month < 1 || month > 12) {
return false;
}
// validate days in month
const daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthLength = daysInMonth[month-1];
if ((month == 2) && ((!(year%4) && year%100) || !(year%400))) {
monthLength = 29;
}
if (day < 1 || day > monthLength) {
return false;
}
// checks have passed
result = true;
}
}
return result;
}

Javascript Calculating year diff error in date?

I am trying to understand the date in JavaScript. But I can't get it.
I create a function that takes two dates and returns a value based on the difference of dates.
Here is the whole code:
function checkDate(birth_date, download_date) {
let yearDiff = download_date.getFullYear() - birth_date.getFullYear();
console.log(yearDiff);
if (yearDiff > 5) return "Not Eligible";
if (yearDiff < 5) return "Eligible";
if (yearDiff == 5) {
// Eligible only if 5 years or low
// If diff is Exact 5 Years Check if Bday is on download date ?
// First Check Month
let monthDiff = download_date.getMonth() - birth_date.getMonth();
if (monthDiff >= 1) {
return "Not Eligible"
}
if (monthDiff <= -1) {
return "Eligible"
}
if (monthDiff = 0) {
// Check Day
let dateDiff = download_date.getDay() - birth_date.getDay();
if (dateDiff <= 0) {
return "Eligible"
} else {
return "Not Eligible"
}
}
}
}
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
let dob = new Date(dob_string.substr(dob_string.indexOf("DOB:") + 4, 11).trim());
let dld = new Date(dl_string.substr(dl_string.indexOf("Download") + 14, 11).trim());
console.log(checkDate(dob,dld));
The is the date is not getting created it says Invalid Date.
I want to check if the DOB difference is 5 more or not.
The problem is the new Date constructor doesn't understand dd/mm/yyyy format and is implemented differently on different browsers. What you need to do is convert it into valid format.
One way is to split it and pass into the constructor like this:
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
let dob = dob_string.substr(dob_string.indexOf("DOB:") + 4, 11).trim();
const splitDOB = dob.split('/')
const validDate = new Date(
parseInt(splitDOB[2], 10),
parseInt(splitDOB[1], 10) - 1,
parseInt(splitDOB[0], 10)
);
The - 1 in the second param is because month is 0-indexed. Then you can process with the logic of your own function.
But I highly recommend using 3rd party lib such as dayjs when working with date/time in JS
so i tested it and even the substrings creates invalid dates.
so i wrote you this:
function checkDate(birth_date, download_date) {
let yearDiff = download_date.getFullYear() - birth_date.getFullYear();
console.log(yearDiff);
if (yearDiff > 5) return "Not Eligible";
if (yearDiff < 5) return "Eligible";
if (yearDiff == 5) {
// Eligible only if 5 years or low
// If diff is Exact 5 Years Check if Bday is on download date ?
// First Check Month
let monthDiff = download_date.getMonth() - birth_date.getMonth();
if (monthDiff >= 1) {
return "Not Eligible"
}
if (monthDiff <= -1) {
return "Eligible"
}
if (monthDiff == 0) {
// Check Day
let dateDiff = download_date.getDay() - birth_date.getDay();
if (dateDiff <= 0) {
return "Eligible"
} else {
return "Not Eligible"
}
}
}
}
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
function filterDate(str) {
const match = str.match(/(\d{1,2}).(\d{1,2}).(\d{4})/);
let year = match[3];
let month = match[2];
let day = match[1];
if (isNaN(year) || isNaN(month) || isNaN(day)) {
throw new Error("no valid date");
}
// fix strings to numbers;
year = +year;
month = +month;
day = +day;
// months begins on 0
month = month - 1;
return new Date(year, month, day);
}
console.log(checkDate(filterDate(dob_string),filterDate(dl_string)));

Invalid date not returning as invalid in IE [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
How to validate a date?
(11 answers)
Closed 4 years ago.
I am using browser date function. I have input like 13/77/7777 which is a invalid date. I do like
new Date('13/77/7777').getTime();
This returns NAN in FF and chrome but in IE it gives a number back. How do i fix this issue.
The value I get with .getTime() in IE11 is 183289406400000.
The date itself comes back as March 18, 7778.
This is because, quite maddeningly, IE11 is parsing 13/77/7777 in mm/dd/yyyy format and coming up with the result of "Month 13 and Day 77 of the Year 7777" which (frustratingly and yet unsurprisingly) works out to March 18, 7778 (if you add 13 months and 77 days to January 1, 7777).
Given that a quick google search turned up no results for any polyfills for the Date constructor in IE11, I suspect the most reasonable fix would be to sanity-check the string before trying to parse the date with the constructor.
With the caveat that while it's probably not as efficient (or as accurate) as it could be, it should serve as a reasonable example to help you get started. Something like this should do:
function isValidDateString(s) {
"use strict";
if (typeof s !== "string") {
return false; // not a string, exit.
}
var parts = s.split("/");
if (parts.length !== 3) {
return false; // unexpected number of slashes. exit.
}
var d31 = [1, 3, 5, 7, 8, 10, 12];
var d30 = [4, 6, 9, 11];
var mm = parseInt(parts[0]);
var dd = parseInt(parts[1]);
var yyyy = parseInt(parts[2]);
// empirical testing in Chrome & IE11 to get this value. YMMV.
var maxYear = 275760;
var isValidYear = !isNaN(yyyy) && yyyy <= maxYear;
var isDivisbleBy4 = (yyyy % 4 === 0);
var isDivisbleBy100 = (yyyy % 100 === 0);
var isDivisbleBy400 = (yyyy % 400 === 0);
var isLeapYear = (isDivisbleBy4 && !isDivisbleBy100) || isDivisbleBy400;
var isValidMonth = !isNaN(mm) && (mm >= 1 && mm <= 12);
if (!isValidMonth) {
return false;
}
var maxDaysInMonth = 28;
if (d31.indexOf(mm) > -1) {
maxDaysInMonth = 31;
} else if (d30.indexOf(mm) > -1) {
maxDaysInMonth = 30;
} else if (isLeapYear) {
maxDaysInMonth = 29;
}
var isValidDay = !isNaN(dd) && (dd > 0 && dd <= maxDaysInMonth);
if (!isValidDay) {
return false;
}
return isValidMonth && isValidDay && isValidYear;
}
var testsThatShouldFail = [
'13/77/7777', // lousy Smarch weather!
'2/29/2018',
'9/12/275761',
'4/31/2016',
'6/35/2019',
];
var testsThatShouldPass = [
'1/1/1900',
'2/29/2000',
'2/29/2016',
'9/12/275760',
'8/16/2018',
];
console.log('should fail', testsThatShouldFail.map(isValidDateString));
console.log('should pass', testsThatShouldPass.map(isValidDateString));

How to exclude weekends between two dates using Moment.js

I am trying to exclude weekends in my JavaScript code. I use moment.js and having difficulty choosing the right variable for 'days'.
So far I have thought that I need to exclude day 6 (saturday) and day 0 (sunday) by changing the weekday variable to count from day 1 to day 5 only. But not sure how it changes.
My jsfiddle is shown here: FIDDLE
HTML:
<div id="myContent">
<input type="radio" value="types" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping1">Free Shipping: (<span id="fsv1" value="5">5</span> to <span id="fsv2" value="10">10</span> working days)</label> </td><br>
<div id="contacts" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative;margin-bottom:25px;">
Contacts
</div>
<input type="radio" value="groups" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping2">Express Shipping: (<span id="esv1" value="3">3</span> to <span id="esv2" value="4">4</span> working days)</label> </td>
<div id="groups" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative">
Groups
</div>
</div>
JavaScript:
var a = 5; //Free shipping between a
var b = 10;//and b
var c = 3;//Express shipping between c
var d = 4;//and d
var now = moment();
var f = "Your item will be delivered between " + now.add("days",a).format("Do MMMM") + " and " + now.add("days",b).format("Do MMMM");
var g = "Your item will be delivered between " + now.add("days".c).format("Do MMMM") + " and " + now.add("days",d).format("Do MMMM");
var h = document.getElementById('contacts');
h.innerHTML = g
var i = document.getElementById('groups');
i.innerHTML = f
$(function() {
$types = $('.syncTypes');
$contacts = $('#contacts');
$groups = $('#groups');
$types.change(function() {
$this = $(this).val();
if ($this == "types") {
$groups.slideUp(300);
$contacts.delay(200).slideDown(300);
}
else if ($this == "groups") {
$contacts.slideUp(300);
$groups.delay(200).slideDown(300);
}
});
});
Here you go!
function addWeekdays(date, days) {
date = moment(date); // use a clone
while (days > 0) {
date = date.add(1, 'days');
// decrease "days" only if it's a weekday.
if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
days -= 1;
}
}
return date;
}
You call it like this
var date = addWeekdays(moment(), 5);
I used .isoWeekday instead of .weekday because it doesn't depend on the locale (.weekday(0) can be either Monday or Sunday).
Don't subtract weekdays, i.e addWeekdays(moment(), -3) otherwise this simple function will loop forever!
Updated JSFiddle http://jsfiddle.net/Xt2e6/39/ (using different momentjs cdn)
Those iteration looped solutions would not fit my needs.
They were too slow for large numbers.
So I made my own version:
https://github.com/leonardosantos/momentjs-business
Hope you find it useful.
https://github.com/andruhon/moment-weekday-calc plugin for momentJS might be helpful for similar tasks
It does not solves the exact problem, but it is able to calculate specific weekdays in the range.
Usage:
moment().isoWeekdayCalc({
rangeStart: '1 Apr 2015',
rangeEnd: '31 Mar 2016',
weekdays: [1,2,3,4,5], //weekdays Mon to Fri
exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays
}) //returns 260 (260 workdays excluding two public holidays)
If you want a pure JavaScript version (not relying on Moment.js) try this...
function addWeekdays(date, days) {
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
var check = date.getDay(); // turns the date into a number (0 to 6)
if (check == 0 || check == 6) {
// Do nothing it's the weekend (0=Sun & 6=Sat)
}
else{
counter++; // It's a weekday so increase the counter
}
}
}
return date;
}
You call it like this...
var date = addWeekdays(new Date(), 3);
This function checks each next day to see if it falls on a Saturday (day 6) or Sunday (day 0). If true, the counter is not increased yet the date is increased.
This script is fine for small date increments like a month or less.
I would suggest adding a function to the moment prototype.
Something like this maybe? (untested)
nextWeekday : function () {
var day = this.clone(this);
day = day.add('days', 1);
while(day.weekday() == 0 || day.weekday() == 6){
day = day.add("days", 1);
}
return day;
},
nthWeekday : function (n) {
var day = this.clone(this);
for (var i=0;i<n;i++) {
day = day.nextWeekday();
}
return day;
},
And when you're done and written some tests, send in a pull request for bonus points.
d1 and d2 are moment dates passed as an argument to calculateBusinessDays
calculateBusinessDays(d1, d2) {
const days = d2.diff(d1, "days") + 1;
let newDay: any = d1.toDate(),
workingDays: number = 0,
sundays: number = 0,
saturdays: number = 0;
for (let i = 0; i < days; i++) {
const day = newDay.getDay();
newDay = d1.add(1, "days").toDate();
const isWeekend = ((day % 6) === 0);
if (!isWeekend) {
workingDays++;
}
else {
if (day === 6) saturdays++;
if (day === 0) sundays++;
}
}
console.log("Total Days:", days, "workingDays", workingDays, "saturdays", saturdays, "sundays", sundays);
return workingDays;
}
If you want a version of #acorio's code sample which is performant (using #Isantos's optimisation) and can deal with negative numbers use this:
moment.fn.addWorkdays = function (days) {
// Getting negative / positive increment
var increment = days / Math.abs(days);
// Looping weeks for each full 5 workdays
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
// Account for starting on Saturdays and Sundays
if(date.isoWeekday() === 6) { date.add(-increment, 'days'); }
else if(date.isoWeekday() === 7) { date.add(-2 * increment, 'days'); }
// Adding / removing remaining days in a short loop, jumping over weekends
var remaining = days % 5;
while(remaining != 0) {
date.add(increment, 'days');
if(date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
remaining -= increment;
}
return date;
};
See Fiddle here: http://jsfiddle.net/dain/5xrr79h0/
Edit: now fixed issue adding 5 days to a day initially on a weekend
I know this question was posted long ago, but in case somebody bump on this, here is optimized solution using moment.js:
function getBusinessDays(startDate, endDate){
var startDateMoment = moment(startDate);
var endDateMoment = moment(endDate)
var days = Math.round(startDateMoment.diff(endDateMoment, 'days') - startDateMoment .diff(endDateMoment, 'days') / 7 * 2);
if (endDateMoment.day() === 6) {
days--;
}
if (startDateMoment.day() === 7) {
days--;
}
return days;
}
const calcBusinessDays = (d1, d2) => {
// Calc all days used including last day ( the +1 )
const days = d2.diff(d1, 'days') + 1;
console.log('Days:', days);
// how many full weekends occured in this time span
const weekends = Math.floor( days / 7 );
console.log('Full Weekends:', weekends);
// Subtract all the weekend days
let businessDays = days - ( weekends * 2);
// Special case for weeks less than 7
if( weekends === 0 ){
const cur = d1.clone();
for( let i =0; i < days; i++ ){
if( cur.day() === 0 || cur.day() === 6 ){
businessDays--;
}
cur.add(1, 'days')
}
} else {
// If the last day is a saturday we need to account for it
if (d2.day() === 6 ) {
console.log('Extra weekend day (Saturday)');
businessDays--;
}
// If the first day is a sunday we need to account for it
if (d1.day() === 0) {
console.log('Extra weekend day (Sunday)');
businessDays--;
}
}
console.log('Business days:', businessDays);
return businessDays;
}
This can be done without looping between all dates in between.
// get nb of weekend days
var startDateMonday = startDate.clone().startOf('isoWeek');
var endDateMonday = endDate.clone().startOf('isoWeek');
var nbWeekEndDays = 2 * endDateMonday.diff(startDateMonday, 'days') / 7;
var isoDayStart = startDate.isoWeekday();
if (isoDayStart > 5) // starts during the weekend
{
nbWeekEndDays -= (8 - isoDayStart);
}
var isoDayEnd = endDate.isoWeekday();
if (isoDayEnd > 5) // ends during the weekend
{
nbWeekEndDays += (8 - isoDayEnd);
}
// if we want to also exlcude holidays
var startOfStartDate = startDate.clone().startOf('day');
var nbHolidays = holidays.filter(h => {
return h.isSameOrAfter(startOfStartDate) && h.isSameOrBefore(endDate);
}).length;
var duration = moment.duration(endDate.diff(startDate));
duration = duration.subtract({ days: nbWeekEndDays + nbHolidays });
var nbWorkingDays = Math.floor(duration.asDays()); // get only nb of complete days
I am iterating from start date to end date and only counting days which are weekdays.
const calculateBusinessDays = (start_date, end_date) => {
const d1 = start_date.clone();
let num_days = 0;
while(end_date.diff(d1.add(1, 'days')) > 0) {
if ([0, 6].includes(d1.day())) {
// Don't count the days
} else {
num_days++;
}
}
return num_days;
}

How to validate a date?

I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.
How can I do this with any date?
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid() gives desired result.
Se post HERE
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
My function returns true if is a valid date otherwise returns false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}

Categories