22

I have datepicker, but I could not find a way to validate if the user's entry is a date or not AND if it follows the required format (format: yyyy-mm-dd)

This is my datepicker:

$("input[name='date']").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, numberOfMonths: 3, showButtonPanel: true});

I looked on this solution, "How to validate datepicker to forbid/reject certain dates?". It looks simple enough, but it only checks whether it's a weekend. It does not checks it the user entered a date, a random number or a typo (1231....30-30-2011...30/30/2011...212-565-565...etc.).

Please fiddle with my fiddle: http://jsfiddle.net/MDa4A/




Additional info (11-10-2011):
(Try these jsFiddles and type 0-0-0 or 0/0/0)

I used your answers to come up with a solution. It works when I use the format "yy-mm-dd": http://jsfiddle.net/LyEvQ/

BUT it is totally useless when I use a different format (Ej.: "mm/dd/yy"): http://jsfiddle.net/LyEvQ/1/

I need both to work. Can you please help

Community
  • 1
  • 1
Omar
  • 11,783
  • 21
  • 84
  • 114

3 Answers3

44
if (Date.parse("some string")) {
   //Valid date
} else {
  //Not a valid date
}
Asmor
  • 5,043
  • 6
  • 32
  • 42
15

Something like this should work:

jQuery.validator.addMethod("customDateValidator",
    function(value, element) {
        try { jQuery.datepicker.parseDate("mm/dd/yyyy", value); return true; }
        catch(e) { 
            return false;
        }
    },
    "Please enter a valid date"
);

$("input[name='date']").rules("add", { customDateValidator:true });
James Johnson
  • 45,496
  • 8
  • 73
  • 110
  • can you please give me a jsFiddle example? -I tried your answer and could not make it work by myself =( – Omar Nov 08 '11 at 22:57
  • 2
    If you're using datepicker anyway (you probably are), this seems like a better validator than just simply using `Date.parse` – VoidKing Aug 19 '13 at 20:45
  • 2
    If some get error " Missing number at position 10" or parse not working then try `"mm/dd/yy"` instead of "mm/dd/yyyy" – Rikin Patel Jun 30 '14 at 16:34
  • 1
    I've never seen the jQuery validator put to use. Very cool. Upvote for you. Thanks – BrianLegg Jan 25 '17 at 17:17
  • I think it is not a good idea to validate dates by handling the exceptions. @James Hill has provided a better solution for that. – Jamshaid K. Feb 24 '18 at 12:25
  • datepicker that is setup on an input element still allows the entering in of an invalid date - so some kind of a check for valid dates are needed Unfortunately Date.parse is not it. Date.parse will accept integers like 1111 as a valid date. – John Foll Jun 20 '23 at 23:14
10

Use the Date.parse() method to check if a date is valid:

var timestamp = Date.parse($("input[name='date']").val()) 

if (isNaN(timestamp) == false) { 
    var d = new Date(timestamp); 
} 
James Hill
  • 60,353
  • 20
  • 145
  • 161
  • 1
    `Date.parse` has inconsistent implementations across browsers, and I wouldn't use it as a validator. For example, integers +-20,000 or so are valid Dates (`Date.parse("200000")`), but I wouldn't want to accept that as input. – nrabinowitz Nov 08 '11 at 21:58
  • 4
    and it neither validates if the date is valid, only checks that day is between 1 and 31, month between 1 and 12, etc. `Date.parse('2000-11-31') == Date.parse('2000-12-01')` – kpull1 Mar 14 '13 at 12:29
  • I would use: if(isNaN(Date.parse($("input[name='date']").val()){isNotDate}, writing less code should be the overall goal, atleast it is for me. – TGarrett Sep 18 '15 at 17:04
  • 3
    @TGarrett, don't you think that readable, maintainable code should be the goal? – James Hill Sep 19 '15 at 14:56
  • @jameshill, yes'sir, readability is a huge concern when it comes to all code and having the developer after you who will make changes to your code, should be super easy for them to pick up, no matter what coding level the person may be at. What I did, was cleaned up the pieces that seemed redundant to me, such as having an equal operator for a bolean when you can simply remove that and add in any logic operator in there such as "!", for most who have been programming a for some time(1-2years), will be able to pick-up on it very fast. Different coding styles are another discussion that happens: – TGarrett Sep 21 '15 at 15:05
  • Date.parse("this is a BAD date 2029") returns a VALID date. The year at the end of the strings fools the parser. – Juan Nov 13 '20 at 22:31
  • Date.parse(myDateVariable) allows stuff like 1111 which is clearly not a date. It disallows 31/31/2023 which is good. – John Foll Jun 20 '23 at 22:31