简体   繁体   English

如何验证通过 javascript 输入的日期时间字段?

[英]How do i validate a datetime field input through javascript?

I have an HTML page that has several fields and one of them is to select DateTime using jquery plugin, which lets user to select DateTime like: 2011-06-05 07:10 or 2011-03-05 11:10 etc.My problem is how do I validate this field value before posting it to server.I want to use javascript to ensure that the field value is only DateTime in this format and is not a invalid value like "2231" or "afaf" . I have an HTML page that has several fields and one of them is to select DateTime using jquery plugin, which lets user to select DateTime like: 2011-06-05 07:10 or 2011-03-05 11:10 etc.My problem是如何在将其发布到服务器之前验证此字段值。我想使用 javascript 确保该字段值仅是此格式的 DateTime 并且不是像"2231""afaf"这样的无效值。

If the user wants to tamper with the data he sends, he does so by circumventing the jQuery plugin as well as any additional code for validation on the client.如果用户想要篡改他发送的数据,他可以通过绕过 jQuery 插件以及任何附加的客户端验证代码来实现。 Then it makes no sense to write additional code for validation on the client.那么在客户端上编写额外的验证代码是没有意义的。

If the user does not want to tamper with the data he sends, the jQuery plugin alone should ensure an appropriate format.如果用户不想篡改他发送的数据,则单独的 jQuery 插件应确保适当的格式。 Then it makes no sense to write additional code for validation on the client.那么在客户端上编写额外的验证代码是没有意义的。

Validate this field on the server only.仅在服务器上验证此字段。

You MUST validate on the server too.您也必须在服务器上进行验证。

The simplest way on the client to test a date string like that is to use Date.parse like this (I am not testing the format other than using date parse. If the user enters another format, you will need to test that too)客户端上测试日期字符串的最简单方法是像这样使用 Date.parse (除了使用日期解析之外,我没有测试格式。如果用户输入另一种格式,您也需要对其进行测试)

var DT = Date.parse(DateTime.replace("-","/","g"));
if (isNaN(DT)) {
  alert('Invalid date');
  return false;
}
var testDate = new Date(DT);
var parts = DateTime.split(" ")[0].split("-");
if (testDate.getFullYear() != parseInt(parts[0]) ||
    testDate.getMonth() != parseInt(parts[1]-1) ||
    testDate.getDate() != parseInt(parts[2])) {
  alert('Invalid date');
  return false;
}

This is of course completely unnecessary if you use a widget to create the date.如果您使用小部件来创建日期,这当然是完全没有必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM