Question

i need to validate date year between 1600 and 9999 by using regex. Does anybody knows the best way to do this? For example with this given format dd/mm/yyyy.

Was it helpful?

Solution

Assuming you can trust the format, it would be easiest to just split on / and check that the year falls in this range.

var year = date.split("/").pop();
valid = year >= 1600 && year <= 9999

If you have to use a regex:

/\d\d\/\d\d\/(1[6-9]\d\d|[2-9]\d\d\d)/

may be what you are after.

If you need more sophisticated date parsing, you should use something like moment.js

var year = moment(date, "DD/MM/YYYY").year();

OTHER TIPS

If you're using Javascript, just have the value as a string, and push it into a Date() object. No need for regular expressions.

date = new Date("24/12/2014") //Valid date
date = new Date("40/10/2014") //Invalid date

//Detect whether date is valid or not:
if( !isNan( date.valueOf() ) ) {    //You can also use date.getTime() instead
    //Valid Date
} else {
    //Invalid Date
}

from here, you can just extract out the date object to your needs like date.getMonth(). Enjoy!

More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Don't use a regex for this, try the following function:

function isValidDate(dateString)
{
    // 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);

    // Check the ranges of month and year
    if(year < 1600 || year > 9999 || month == 0 || 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
    return day > 0 && day <= monthLength[month - 1];
};

WORKING EXAMPLE:

http://jsfiddle.net/tuga/8rj6Q/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top