开发者

Validate DateTimeOffset and TimeSpan using Attribute Validators in ASP.NET MVC

So I've got entities set up with Entity Framework that have some properties of types String, DateTimeOffset and TimeSpan. For performing validation on th开发者_如何学运维e Strings, I've used fairly straightforward attributes like "[Required]" or "[StringLength]", and the control used is a textbox.

My issue now is for the DateTimeOffset and TimeSpan, I'm uncertain what control to use, but even more uncertain about what attributes to use to validate the input.

Any suggestions?


I don't believe there is a way to infer the data type from input. Treating it as needed by business logic seems to be the only path.


Since it's a timespan, you can get the minutes equivalent and do an IsNumeric call on that - which is a simple custom validation function.

If your calculating the time diff using two dates, you can use the DateDiff function to calculate the difference and get the timespan - but if you already have this, remember a timespan can be represented as a number of units of time, so use IsNumeric using a custom function.

Otherwise, if you don't want to write a custom validation, the. The easiest way to do it is use the RangeValidator Attribute. Place in the min and max possible numbers, just to be safe, and when validation occurs using this attribute, it will return False if its not a numeric number anyway, so you get bad string validation from that alone, and you are also able to validate the range of possible values of the timespan - if range isn't important, then just set the upper limit to a safe value like several million minutes or something (eg: Long.MaxValue or Integer.MaxValue).

You can also pass Ticks as the value of the timespan to compare to the range, so TimeSpan.Ticks() I believe, but just sending the text box to RangeValidator is enough, it will check that it ain't text characters and check for range and voila, validation done and no need for custom validation.

Let me know how you get along and how else I can help you if needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜