Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/JavaScript: Is it a date? (Validate whether is a date) [duplicate]

Tags:

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

like image 234
Omar Avatar asked Nov 08 '11 16:11

Omar


2 Answers

if (Date.parse("some string")) {
   //Valid date
} else {
  //Not a valid date
}
like image 58
Asmor Avatar answered Oct 20 '22 20:10

Asmor


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 });
like image 45
James Johnson Avatar answered Oct 20 '22 20:10

James Johnson