jQuery / JavaScript: ¿Es una fecha? (Validar si es una fecha) [duplicar]

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

preguntado el 08 de noviembre de 11 a las 16:11

3 Respuestas

if (Date.parse("some string")) {
   //Valid date
} else {
  //Not a valid date

respondido 08 nov., 11:20

can you please elaborate a little more? - Omar

This is not correct, as it returns number instead of NaN for e.g. 2014-11-31 which doesn't exist. - wieczorek1990

Algo como esto debería funcionar:

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

respondido 08 nov., 11:20

can you please give me a jsFiddle example? -I tried your answer and could not make it work by myself =( - Omar

If you're using datepicker anyway (you probably are), this seems like a better validator than just simply using Date.parse - VoidKing

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

I've never seen the jQuery validator put to use. Very cool. Upvote for you. Thanks - BrianLegg

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.

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

respondido 08 nov., 11:20

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

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

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

@TGarrett, don't you think that readable, maintainable code should be the goal? - James Hill

@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

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.