我正在尝试检查用户输入字段以查看它是否在将来以及它是否为dd / mm / yyyy格式但我不知道为什么我的代码的格式部分根本不会触发!实际上似乎没有任何东西可以用于Jsfiddle,但至少我的“未来检查日期”功能在本地工作。
我不知道正确的解决方法。
为了解释这一点,我创建了这个FIDDLE
这是我的完整JavaScript代码。我需要坚持使用纯JavaScript:
function checkdate(){
//var sendDate = document.getElementById('send_year').value + '/' + document.getElementById('send_month').value + '/' + document.getElementById('send_day').value;
var sendDate = document.getElementById('returning_date').value;
sendDate = new Date(Date.parse(sendDate.replace(/-/g,' ')))
today = new Date();
today.setHours(0,0,0,0)
if (sendDate < today) {
//alert('The date can\'t be in the past. Please pick another date.');
document.getElementById('error8').innerHTML = 'The date can\'t be in the past. Please pick another date.';
return false;
}
else
{
document.getElementById('error8').innerHTML = '';
}
if(sendDate.match(/^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])/))
{
alert('works out');
}
}
有人可以就此问题提出建议吗?
提前致谢。
答案 0 :(得分:1)
一个问题是您正在尝试运行sendDate.match,但sendDate已转换为Date对象,因此它没有匹配方法。
您应该在将正则表达式转换为日期之前运行它,在验证中,您通常会在运行进一步验证(如范围验证)之前检查输入是否符合格式。
答案 1 :(得分:1)
应始终手动解析日期字符串,不应允许Date构造函数或Date.parse解析字符串(Date构造函数以与Date.parse完全相同的方式解析字符串)。
要解析和验证日期字符串是相当简单的,只需解析字符串并查看是否获得有效日期:
/* Parse a string in d/m/y format. Separator can be any non–digit
** Avoid conversion of two digit dates to 20th century
** Returns an invalid Date if string is not a valid date (per ECMA-262)
**
** @param {string} s - Date string to parse
** @returns {Date}
*/
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date();
d.setHours(0,0,0,0);
d.setFullYear(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
// Test valid date
document.write(parseDMY('23/01/2016'));
// Test invalid date
document.write('<br>' + parseDMY('35/12/2016'));
请注意,这将接受像1/5/16这样的日期,并且视为0016年5月1日。如果您想保证日期和月份值有两位数和年份,请添加:
/^\d\d\D\d\d\D\d{4}$/.test(s)
到最后的验证测试。但是,由于人们通常不会将日期写为“2016年8月1日”,因此我不喜欢强制日期和月份的2位数,他们使用“1/8/2016”。
答案 2 :(得分:0)
首先,函数需要包含在<head>
中(点击js选项卡中的cog),否则无法找到该函数。
但您的主要问题是您使用的是欧式日期格式,因此在创建日期时会出现“无效日期”异常。请参阅this question,了解如何将其转换为美国风格,并将其用于Date
对象(查看the reference以了解所有可能的用途)
答案 3 :(得分:0)
我的建议是:
bob - 555
mary - 888
&#13;
bob - 444 -- mary does not exist in this table
&#13;