简体   繁体   English

asp.net mvc datetime通过客户端日期格式的动态验证

[英]asp.net mvc datetime dynamic validation by clients date format

I have a Custom Attribute for DateTime validation with given dateformat and also javascript validator which are provide me both client side and server side validation. 我有给定dateformat的DateTime验证的自定义属性,还有javascript验证程序,它们为我提供了客户端和服务器端验证。 But now I should change my datetime validation so that it would be performed according clients local DateTime format and I do not know how. 但是现在我应该更改日期时间验证,以便根据客户端本地的DateTime格式执行它,而我不知道如何进行。

I couldn't find anything that help me. 我找不到任何可以帮助我的东西。

So please advise me how can I implement at least client side DateTime validation or how can I get client's date format by javascript. 因此,请告诉我如何至少实现客户端DateTime验证或如何通过javascript获取客户端的日期格式。

If you can determine the locale of your user, you can use .Net globalization classes to assist with server-side parsing of date time strings. 如果可以确定用户的语言环境,则可以使用.Net全球化类来协助服务器端解析日期时间字符串。 For example: 例如:

// Parsed as January 4th
var dt1 = DateTime.Parse("1/4/2013", new CultureInfo("en-US"));

// Parsed as April 1st
var dt2 = DateTime.Parse("1/4/2013", new CultureInfo("en-GB"));

But the best thing to do is avoid this entirely. 但是最好的办法是完全避免这种情况。 In your JavaScript code, get the value back as an ISO8601 string - which is culture invariant. 在您的JavaScript代码中,以ISO8601字符串的形式返回值-这是区域性不变的。 Native browser support for this varies. 本机浏览器对此的支持各不相同。 The built-in functions work in IE9+. 内置功能可在IE9 +中使用。

// This returns an ISO formatted date, in UTC.
var s = yourDate.ToISOString();

One way to get full browser support, and get an ISO date without converting to UTC, is to use the moment.js library, where ISO8601 is the default format: 获得完全浏览器支持并获得ISO日期而不转换为UTC的一种方法是使用moment.js库,其中ISO8601是默认格式:

// This returns an ISO formatted date, with the user's local offset.
var s = moment(yourDate).format();

// This returns an ISO formatted date, in UTC.
var s = moment(yourDate).utc().format();

When you send these values to the server, you can parse them in your .Net code without concern for culture. 将这些值发送到服务器时,可以在.Net代码中解析它们,而无需担心文化。 The format is already culture invariant. 格式已经是文化不变的。 To prevent the server's time zone from interfering, you should parse them as a DateTimeOffset : 为了防止服务器的时区受到干扰,您应该将它们解析为DateTimeOffset

// assuming this is an ISO value you got from the client:
var s = "2013-04-20T09:00:00-07:00";

// simply parse it
var dto = DateTimeOffset.Parse(s);

// if you don't care about the offset at this point:
var dt = dto.DateTime;

Of course, if you want to fail gracefully, you can do this instead: 当然,如果您想正常地失败,可以这样做:

DateTimeOffset dto;
var isValid = DateTimeOffset.TryParse(s, out dto);

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

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