How to validate a date?

2018-12-31 13:40发布

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?

12条回答
柔情千种
2楼-- · 2018-12-31 14:01

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;
}
查看更多
骚的不知所云
3楼-- · 2018-12-31 14:03

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));

查看更多
伤终究还是伤i
4楼-- · 2018-12-31 14:04

This is JS6 (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]);
查看更多
临风纵饮
5楼-- · 2018-12-31 14:04

Though this was raised long ago, still a most wanted validation. I found an interesting blog with few function.

/* Please use these function to check the reuslt only. do not check for otherewise. other than utiljs_isInvalidDate

Ex:-

utiljs_isFutureDate() retuns only true for future dates. false does not mean it is not future date. it may be an invalid date.

practice :

call utiljs_isInvalidDate first and then use the returned date for utiljs_isFutureDate()

var d = {};

if(!utiljs_isInvalidDate('32/02/2012', d))

if(utiljs_isFutureDate(d))

//date is a future date

else

// date is not a future date



 */

function utiljs_isInvalidDate(dateStr, returnDate) {

    /*dateStr | format should be dd/mm/yyyy, Ex:- 31/10/2017

     *returnDate will be in {date:js date object}.

     *Ex:- if you only need to check whether the date is invalid,

     * utiljs_isInvalidDate('03/03/2017')

     *Ex:- if need the date, if the date is valid,

     * var dt = {};

     * if(!utiljs_isInvalidDate('03/03/2017', dt)){

     *  //you can use dt.date

     * }

     */

    if (!dateStr)
        return true;
    if (!dateStr.substring || !dateStr.length || dateStr.length != 10)
        return true;
    var day = parseInt(dateStr.substring(0, 2), 10);
    var month = parseInt(dateStr.substring(3, 5), 10);
    var year = parseInt(dateStr.substring(6), 10);
    var fullString = dateStr.substring(0, 2) + dateStr.substring(3, 5) + dateStr.substring(6);
    if (null == fullString.match(/^\d+$/)) //to check for whether there are only numbers
        return true;
    var dt = new Date(month + "/" + day + "/" + year);
    if (dt == 'Invalid Date' || isNaN(dt)) { //if the date string is not valid, new Date will create this string instead
        return true;
    }
    if (dt.getFullYear() != year || dt.getMonth() + 1 != month || dt.getDate() != day) //to avoid 31/02/2018 like dates
        return true;
    if (returnDate)
        returnDate.date = dt;
    return false;
}

function utiljs_isFutureDate(dateStrOrObject, returnDate) {
    return utiljs_isFuturePast(dateStrOrObject, returnDate, true);
}

function utiljs_isPastDate(dateStrOrObject, returnDate) {
    return utiljs_isFuturePast(dateStrOrObject, returnDate, false);
}

function utiljs_isValidDateObjectOrDateString(dateStrOrObject, returnDate) { //this is an internal function
    var dt = {};
    if (!dateStrOrObject)
        return false;
    if (typeof dateStrOrObject.getMonth === 'function')
        dt.date = new Date(dateStrOrObject); //to avoid modifying original date
    else if (utiljs_isInvalidDate(dateStrOrObject, dt))
        return false;
    if (returnDate)
        returnDate.date = dt.date;
    return true;

}

function utiljs_isFuturePast(dateStrOrObject, returnDate, isFuture) { //this is an internal function, please use isFutureDate or isPastDate function
    if (!dateStrOrObject)
        return false;
    var dt = {};
    if (!utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt))
        return false;
    today = new Date();
    today.setHours(0, 0, 0, 0);
    if (dt.date)
        dt.date.setHours(0, 0, 0, 0);
    if (returnDate)
        returnDate.date = dt.date;
    //creating new date using only current d/m/y. as td.date is created with string. otherwise same day selection will not be validated.
    if (isFuture && dt.date && dt.date.getTime && dt.date.getTime() > today.getTime()) {
        return true;
    }
    if (!isFuture && dt.date && dt.date.getTime && dt.date.getTime() < today.getTime()) {
        return true;
    }
    return false;
}

function utiljs_isLeapYear(dateStrOrObject, returnDate) {
    var dt = {};
    if (!dateStrOrObject)
        return false;
    if (utiljs_isValidDateObjectOrDateString(dateStrOrObject, dt)) {
        if (returnDate)
            returnDate.date = dt.date;
        return dt.date.getFullYear() % 4 == 0;
    }
    return false;
}

function utiljs_firstDateLaterThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() > dt2.date.getTime())
        return true;
    return false;
}

function utiljs_isEqual(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() == dt2.date.getTime())
        return true;
    return false;
}

function utiljs_firstDateEarlierThanSecond(firstDate, secondDate, returnFirstDate, returnSecondDate) {
    if (!firstDate || !secondDate)
        return false;
    var dt1 = {},
    dt2 = {};
    if (!utiljs_isValidDateObjectOrDateString(firstDate, dt1) || !utiljs_isValidDateObjectOrDateString(secondDate, dt2))
        return false;
    if (returnFirstDate)
        returnFirstDate.date = dt1.date;
    if (returnSecondDate)
        returnSecondDate.date = dt2.date;
    dt1.date.setHours(0, 0, 0, 0);
    dt2.date.setHours(0, 0, 0, 0);
    if (dt1.date.getTime && dt2.date.getTime && dt1.date.getTime() < dt2.date.getTime())
        return true;
    return false;
}

copy the whole code into a file and include.

hope this helps.

查看更多
君临天下
6楼-- · 2018-12-31 14:07

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]);
}
查看更多
忆尘夕之涩
7楼-- · 2018-12-31 14:07

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

查看更多
登录 后发表回答