jQuery/JavaScript:是约会吗?(验证是否为日期)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8054009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:32:27  来源:igfitidea点击:

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

javascriptjqueryvalidationdatedatepicker

提问by Omar

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)

我有日期选择器,但我找不到一种方法来验证用户的输入是否为日期以及它是否遵循所需的格式(格式: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.).

我查看了这个解决方案,“如何验证日期选择器以禁止/拒绝某些日期?”。它看起来很简单,但它只检查是否是周末。它不会检查用户输入的日期、随机数或拼写错误(1231.....30-30-2011...30/30/2011...212-565-565...等) .

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

请摆弄我的小提琴:http: //jsfiddle.net/MDa4A/




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




附加信息(11-10-2011):(
试试这些jsFiddles并输入0-0-0或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/

我用你的答案想出了一个解决方案。当我使用格式“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/

但它是完全无用的,当我使用不同的格式(EJ .:“MM / DD / YY”) http://jsfiddle.net/LyEvQ/1/

I need both to work. Can you please help

我需要两者都工作。你能帮忙吗

回答by Asmor

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

回答by James Johnson

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

回答by James Hill

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

使用该Date.parse()方法检查日期是否有效:

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

if (isNaN(timestamp) == false) { 
    var d = new Date(timestamp); 
}