0

I've tried using the following code to validate a date:

var date = Date.parse(text);

if (isNaN(date)) {
      // Invalid date
}

This does allow m/d/y and yyyy-mm-dd to be valid, but it also allows, for example, a single digit to be valid.

I would like a date function that allows these two formats, m/d/y and yyyy-mm-dd, but is more strict in not allowing just digits.

Chain
  • 597
  • 2
  • 8
  • 24
  • You should use a regular expression. Can you be a little more specific? "but is more strict" doesn't tell us much. – ZeroBased_IX Jul 25 '14 at 23:13
  • http://www.regular-expressions.info/dates.html – Mike Bell Jul 25 '14 at 23:16
  • Sure. The Date.parse allows up to 6 digits to be valid. I would like to make sure they have separators (slashes, dashes, or periods), and contain a minimum of 4 digits: like 1/2/14 – Chain Jul 25 '14 at 23:19
  • 1
    Follow the outline of [this answer](http://stackoverflow.com/a/5812341/2055998). – PM 77-1 Jul 25 '14 at 23:21
  • @MikeBell Hi, that link says "matches a date in yyyy-mm-dd", like most of the functions Ive found. I'm not very familiar with writing out my own script with regular expression, so I was hoping to find a script that allows both m/d/y and yyyy-mm-dd. – Chain Jul 25 '14 at 23:22
  • Think your question was answered before: [Javascript: how to validate dates in format MM-DD-YYYY?][1] [1]: http://stackoverflow.com/questions/276479/javascript-how-to-validate-dates-in-format-mm-dd-yyyy regards – mrPim Jul 25 '14 at 23:54

1 Answers1

1

There are many answer to this question.Out of them i think this function is little bit easier(in mm/dd/yyyy)

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[1], 10);
    var month = parseInt(parts[0], 10);
    var year = parseInt(parts[2], 10);

    // Check the ranges of month and year
    if(year < 1000 || year > 3000 || 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];
};

SEE DEMO HERE

You can also take help from HERE

Community
  • 1
  • 1
Roshan
  • 2,144
  • 2
  • 16
  • 28
  • Thanks: for anyone out there trying to solve what I was trying to solve: the comments here helped me see that there was was no magic bullet out there for what I needed. It's best to write your own custom script that checks for what you require. – Chain Jul 27 '14 at 18:55