服务器上的DateTime时间戳验证 [英] Server side Validation for DateTime Stamp

查看:283
本文介绍了服务器上的DateTime时间戳验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,服务器端日期验证是通过IsDate完成的,这在行为上是非常不一致的。我使用了isValid( USdate,DateVar),它可以很好地处理传入的日期,但是当DateVar是日期时间戳时,它将失败。 DateVar中的值可以是任何东西,日期,时间,日期&时间甚至一些无效的数据。如果我将日期掩码与isValid一起使用,则其行为类似于isDate,并且没有任何用处。我如何才能做到这一点。

In my application, server side date validations were done through IsDate which is very inconsistent in behavior. I used isValid("USdate",DateVar), that works fine with incoming dates, but when DateVar is a date time stamp it fails. Values coming in DateVar could be anything, a date, a time, a date & time or even some invalid data. If I use Date mask with isValid, that behaves like isDate and of no use. How I can accomplish this.

推荐答案

所有通过请求到达的日期-通过URL参数,表单提交,cookie ,等等-将是 strings ,而不是日期。

All "dates" that will be arriving via a request - be they via a URL parameter, a form submission, a cookie, etc - will be strings, not dates.

您需要做的是确定允许的字符串格式,并进行验证

What you need to do is to work out what string formats you will allow, and validate them accordingly.

EG:您可能认为 yyyy-mm-dd 可以,但是您不会接受 m / d / yy 。您可以将它们作为三个单独的组件传递给 y m d 。但是您真的不应该尝试接受任何旧格式,因为每种格式都需要有一个验证器,而且那里的收益率递减法则:人们不会期望使用任何格式他们喜欢;他们会期待您的指导。您还需要注意,如果您要求我输入今天的日期,我会给您2015年4月5日的信息。但是对于您来说,这可能代表4月5日。

EG: you might decide that yyyy-mm-dd is OK, but you won't accept m/d/yy. You might pass them as three separate components for y, m and d. But you really oughtn't try to accept any old format, as you will need to have a validator for each format, and there's a law of diminishing returns there: people won't expect to use any format they like; they'll be expecting you to guide them. You also need to be mindful that if you ask me to type in today's date, I'd give you 4/5/2015. But to you that might represent April 5.

给出各种月长和leap年规则,这实际上是查看和输入字符串是否代表一个最简单,最可靠的方法。日期以可接受的格式执行此操作:

Given various month-length and leap-year rules, really the easiest and most reliable way to see if and input string represents a date in an acceptable format do this:


  • 验证格式掩码,例如:如果您接受 yyyy- mm-dd ,则输入必须为 \d {4} -\d {2} -\d {2} 。然后至少您知道字符串已经正确构成。

  • 然后从字符串中提取组件,并尝试使用它们创建日期对象。如果没有错误:可以。

  • 最后一次:检查日期范围内/日期之外的任何日期边界。

  • Validate the format mask, eg: if you're accepting yyyy-mm-dd, then the input needs to be \d{4}-\d{2}-\d{2}. Then at least you know the string has been formed properly.
  • Then extract the components from the string, and attempt to create a date object with them. If it doesn't error: it's OK.
  • Last: check any date boundaries within / outwith which the date needs to fall.

这篇关于服务器上的DateTime时间戳验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆