问题描述
我有一个验证方法,看起来非常简单,因为我在使用格式 mm / dd / yy
时会使用非常相似的东西,但是当我使用 mm / y ...我一直收到无效日期。
I have a validate method which seems pretty simple because I use something very similar when using the format mm/dd/yy
, but when I use mm/y
...I keep getting an invalid date.
这是我的验证:
function validateDate(dateField) {
try{
$.datepicker.parseDate('mm/y', dateField, null);
}
catch(error){
alert(error);
}
}
如果我传递的日期如 05/11
...这个逻辑抱怨日期无效。如果我将格式更改为 mm / dd / yy
并输入 05/11/2011
...那么它说这是有效的。
If I pass in a date like 05/11
...this logic complains that the date is invalid. If I change the format to mm/dd/yy
and enter 05/11/2011
...then it says it is valid.
我在尝试验证 mm / y
模式时是否遗漏了某些内容?
Am I missing something when trying to validate a mm/y
pattern?
推荐答案
不幸的是,您需要为datepicker提供至少一个月的日期才能正确解析日期。如果您将年份退出,则默认为当前年份,因此将06/15解析为dd / mm将为您提供2011-06-15。但如果省略月份或日期,则默认为-1并生成无效日期。
Unfortunately, you need to supply at least a month and day for the datepicker to parse your date properly. If you leave the year out, it defaults to the current year, so parsing "06/15" as "dd/mm" will give you 2011-06-15. But if either month or day are omitted, they default to -1 and will produce an invalid date.
编辑:
如果您只是想确认用户输入了有效的月份和年份,请执行以下操作:
If you are just trying to confirm that the user entered a valid month and year, do this:
$.datepicker.parseDate('dd/mm/y', "01/" + dateField, null);
这篇关于jQuery - 'mm / y'上的datepicker.parseDate导致无效日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!