Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Seth Duncan Avatar asked Apr 28 '11 00:04

Seth Duncan


People also ask

How can we validate date?

Among various kind of data validation, validation of date is one. 1. dd/mm/yyyy or dd-mm-yyyy format.

How do I validate a date in python?

The date validation you want to achieve in python will largely depend on the format of the date you have. The strptime function from the datetime library can be used to parse strings to dates/times.

How do I validate dates in Google forms?

Google Forms does not support response validations for date questions. The workaround is to add a short answer question with the required response validations and add the date range calculations in Formfacade. To use this feature, you need our Gsuite addon. Install this addon to customize Google Forms.


2 Answers

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))  })
like image 195
RobG Avatar answered Sep 17 '22 16:09

RobG


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]); } 
like image 42
Piotr Kwiatek Avatar answered Sep 18 '22 16:09

Piotr Kwiatek